]> git.proxmox.com Git - mirror_edk2.git/blobdiff - MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
Calculate enough space for 2 variables (public key and variable data) instead of...
[mirror_edk2.git] / MdeModulePkg / Universal / Variable / RuntimeDxe / Variable.c
index 553ae2824d1d35fb764be5d4eb5387b28e60d134..7bd9ffb6c5d406b1b566f3a7030f19b3725c7e2f 100644 (file)
@@ -1,10 +1,10 @@
 /** @file\r
 \r
-  Implement all four UEFI Runtime Variable services for the nonvolatile\r
-  and volatile storage space and install variable architecture protocol.\r
+  The common variable operation routines shared by DXE_RUNTIME variable \r
+  module and DXE_SMM variable module.\r
   \r
-Copyright (c) 2006 - 2008, Intel Corporation                                                         \r
-All rights reserved. This program and the accompanying materials                          \r
+Copyright (c) 2006 - 2014, 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
@@ -17,79 +17,78 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 #include "Variable.h"\r
 \r
 VARIABLE_MODULE_GLOBAL  *mVariableModuleGlobal;\r
-EFI_EVENT   mVirtualAddressChangeEvent = NULL;\r
-EFI_HANDLE  mHandle = NULL;\r
 \r
 ///\r
-/// The current Hii implementation accesses this variable many times on every boot.\r
-/// Other common variables are only accessed once. This is why this cache algorithm\r
-/// only targets a single variable. Probably to get an performance improvement out of\r
-/// a Cache you would need a cache that improves the search performance for a variable.\r
+/// Define a memory cache that improves the search performance for a variable.\r
 ///\r
-VARIABLE_CACHE_ENTRY mVariableCache[] = {\r
-  {\r
-    &gEfiGlobalVariableGuid,\r
-    L"Lang",\r
-    0x00000000,\r
-    0x00,\r
-    NULL\r
-  }\r
-};\r
-\r
-VARIABLE_INFO_ENTRY *gVariableInfo = NULL;\r
-\r
-EFI_STATUS\r
-FtwVariableSpace (\r
-  IN EFI_PHYSICAL_ADDRESS   VariableBaseAddress,\r
-  IN UINT8                  *Buffer,\r
-  IN UINTN                  BufferSize\r
-  );\r
-\r
-\r
-/**\r
-  Acquires lock only at boot time. Simply returns at runtime.\r
-\r
-  This is a temperary function which will be removed when\r
-  EfiAcquireLock() in UefiLib can handle the call in UEFI\r
-  Runtimer driver in RT phase.\r
-  It calls EfiAcquireLock() at boot time, and simply returns\r
-  at runtime.\r
-\r
-  @param  Lock         A pointer to the lock to acquire\r
-\r
-**/\r
-VOID\r
-AcquireLockOnlyAtBootTime (\r
-  IN EFI_LOCK  *Lock\r
-  )\r
-{\r
-  if (!EfiAtRuntime ()) {\r
-    EfiAcquireLock (Lock);\r
-  }\r
-}\r
-\r
-/**\r
-  Releases lock only at boot time. Simply returns at runtime.\r
+VARIABLE_STORE_HEADER  *mNvVariableCache      = NULL;\r
 \r
-  This is a temperary function which will be removed when\r
-  EfiReleaseLock() in UefiLib can handle the call in UEFI\r
-  Runtimer driver in RT phase.\r
-  It calls EfiReleaseLock() at boot time, and simply returns\r
-  at runtime.\r
+///\r
+/// The memory entry used for variable statistics data.\r
+///\r
+VARIABLE_INFO_ENTRY    *gVariableInfo         = NULL;\r
 \r
-  @param  Lock         A pointer to the lock to release\r
+///\r
+/// The list to store the variables which cannot be set after the EFI_END_OF_DXE_EVENT_GROUP_GUID\r
+/// or EVT_GROUP_READY_TO_BOOT event.\r
+///\r
+LIST_ENTRY             mLockedVariableList    = INITIALIZE_LIST_HEAD_VARIABLE (mLockedVariableList);\r
 \r
-**/\r
-VOID\r
-ReleaseLockOnlyAtBootTime (\r
-  IN EFI_LOCK  *Lock\r
-  )\r
-{\r
-  if (!EfiAtRuntime ()) {\r
-    EfiReleaseLock (Lock);\r
-  }\r
-}\r
+///\r
+/// The flag to indicate whether the platform has left the DXE phase of execution.\r
+///\r
+BOOLEAN                mEndOfDxe              = FALSE;\r
 \r
+///\r
+/// The flag to indicate whether the variable storage locking is enabled.\r
+///\r
+BOOLEAN                mEnableLocking         = TRUE;\r
+\r
+//\r
+// To prevent name collisions with possible future globally defined variables,\r
+// other internal firmware data variables that are not defined here must be\r
+// saved with a unique VendorGuid other than EFI_GLOBAL_VARIABLE or\r
+// any other GUID defined by the UEFI Specification. Implementations must\r
+// only permit the creation of variables with a UEFI Specification-defined\r
+// VendorGuid when these variables are documented in the UEFI Specification.\r
+//\r
+GLOBAL_VARIABLE_ENTRY mGlobalVariableList[] = {\r
+  {EFI_LANG_CODES_VARIABLE_NAME,             VARIABLE_ATTRIBUTE_BS_RT},\r
+  {EFI_LANG_VARIABLE_NAME,                   VARIABLE_ATTRIBUTE_NV_BS_RT},\r
+  {EFI_TIME_OUT_VARIABLE_NAME,               VARIABLE_ATTRIBUTE_NV_BS_RT},\r
+  {EFI_PLATFORM_LANG_CODES_VARIABLE_NAME,    VARIABLE_ATTRIBUTE_BS_RT},\r
+  {EFI_PLATFORM_LANG_VARIABLE_NAME,          VARIABLE_ATTRIBUTE_NV_BS_RT},\r
+  {EFI_CON_IN_VARIABLE_NAME,                 VARIABLE_ATTRIBUTE_NV_BS_RT},\r
+  {EFI_CON_OUT_VARIABLE_NAME,                VARIABLE_ATTRIBUTE_NV_BS_RT},\r
+  {EFI_ERR_OUT_VARIABLE_NAME,                VARIABLE_ATTRIBUTE_NV_BS_RT},\r
+  {EFI_CON_IN_DEV_VARIABLE_NAME,             VARIABLE_ATTRIBUTE_BS_RT},\r
+  {EFI_CON_OUT_DEV_VARIABLE_NAME,            VARIABLE_ATTRIBUTE_BS_RT},\r
+  {EFI_ERR_OUT_DEV_VARIABLE_NAME,            VARIABLE_ATTRIBUTE_BS_RT},\r
+  {EFI_BOOT_ORDER_VARIABLE_NAME,             VARIABLE_ATTRIBUTE_NV_BS_RT},\r
+  {EFI_BOOT_NEXT_VARIABLE_NAME,              VARIABLE_ATTRIBUTE_NV_BS_RT},\r
+  {EFI_BOOT_CURRENT_VARIABLE_NAME,           VARIABLE_ATTRIBUTE_BS_RT},\r
+  {EFI_BOOT_OPTION_SUPPORT_VARIABLE_NAME,    VARIABLE_ATTRIBUTE_BS_RT},\r
+  {EFI_DRIVER_ORDER_VARIABLE_NAME,           VARIABLE_ATTRIBUTE_NV_BS_RT},\r
+  {EFI_HW_ERR_REC_SUPPORT_VARIABLE_NAME,     VARIABLE_ATTRIBUTE_NV_BS_RT},\r
+  {EFI_SETUP_MODE_NAME,                      VARIABLE_ATTRIBUTE_BS_RT},\r
+  {EFI_KEY_EXCHANGE_KEY_NAME,                VARIABLE_ATTRIBUTE_NV_BS_RT_AT},\r
+  {EFI_PLATFORM_KEY_NAME,                    VARIABLE_ATTRIBUTE_NV_BS_RT_AT},\r
+  {EFI_SIGNATURE_SUPPORT_NAME,               VARIABLE_ATTRIBUTE_BS_RT},\r
+  {EFI_SECURE_BOOT_MODE_NAME,                VARIABLE_ATTRIBUTE_BS_RT},\r
+  {EFI_KEK_DEFAULT_VARIABLE_NAME,            VARIABLE_ATTRIBUTE_BS_RT},\r
+  {EFI_PK_DEFAULT_VARIABLE_NAME,             VARIABLE_ATTRIBUTE_BS_RT},\r
+  {EFI_DB_DEFAULT_VARIABLE_NAME,             VARIABLE_ATTRIBUTE_BS_RT},\r
+  {EFI_DBX_DEFAULT_VARIABLE_NAME,            VARIABLE_ATTRIBUTE_BS_RT},\r
+  {EFI_DBT_DEFAULT_VARIABLE_NAME,            VARIABLE_ATTRIBUTE_BS_RT},\r
+  {EFI_OS_INDICATIONS_SUPPORT_VARIABLE_NAME, VARIABLE_ATTRIBUTE_BS_RT},\r
+  {EFI_OS_INDICATIONS_VARIABLE_NAME,         VARIABLE_ATTRIBUTE_NV_BS_RT},\r
+  {EFI_VENDOR_KEYS_VARIABLE_NAME,            VARIABLE_ATTRIBUTE_BS_RT},\r
+};\r
+GLOBAL_VARIABLE_ENTRY mGlobalVariableList2[] = {\r
+  {L"Boot####",                              VARIABLE_ATTRIBUTE_NV_BS_RT},\r
+  {L"Driver####",                            VARIABLE_ATTRIBUTE_NV_BS_RT},\r
+  {L"Key####",                               VARIABLE_ATTRIBUTE_NV_BS_RT},\r
+};\r
 \r
 /**\r
   Routine used to track statistical information about variable usage. \r
@@ -102,12 +101,12 @@ ReleaseLockOnlyAtBootTime (
   the transaction. Data is allocated by this routine, but never\r
   freed.\r
 \r
-  @param[in] VariableName   Name of the Variable to track\r
-  @param[in] VendorGuid     Guid of the Variable to track\r
-  @param[in] Volatile       TRUE if volatile FALSE if non-volatile\r
-  @param[in] Read           TRUE if GetVariable() was called\r
-  @param[in] Write          TRUE if SetVariable() was called\r
-  @param[in] Delete         TRUE if deleted via SetVariable()\r
+  @param[in] VariableName   Name of the Variable to track.\r
+  @param[in] VendorGuid     Guid of the Variable to track.\r
+  @param[in] Volatile       TRUE if volatile FALSE if non-volatile.\r
+  @param[in] Read           TRUE if GetVariable() was called.\r
+  @param[in] Write          TRUE if SetVariable() was called.\r
+  @param[in] Delete         TRUE if deleted via SetVariable().\r
   @param[in] Cache          TRUE for a cache hit.\r
 \r
 **/\r
@@ -126,26 +125,24 @@ UpdateVariableInfo (
 \r
   if (FeaturePcdGet (PcdVariableCollectStatistics)) {\r
 \r
-    if (EfiAtRuntime ()) {\r
-      // Don't collect statistics at runtime\r
+    if (AtRuntime ()) {\r
+      // Don't collect statistics at runtime.\r
       return;\r
     }\r
 \r
     if (gVariableInfo == NULL) {\r
       //\r
-      // on the first call allocate a entry and place a pointer to it in\r
-      // the EFI System Table\r
+      // On the first call allocate a entry and place a pointer to it in\r
+      // the EFI System Table.\r
       //\r
       gVariableInfo = AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY));\r
       ASSERT (gVariableInfo != NULL);\r
 \r
       CopyGuid (&gVariableInfo->VendorGuid, VendorGuid);\r
-      gVariableInfo->Name = AllocatePool (StrLen (VariableName));\r
+      gVariableInfo->Name = AllocatePool (StrSize (VariableName));\r
       ASSERT (gVariableInfo->Name != NULL);\r
       StrCpy (gVariableInfo->Name, VariableName);\r
       gVariableInfo->Volatile = Volatile;\r
-\r
-      gBS->InstallConfigurationTable (&gEfiVariableInfoGuid, gVariableInfo);\r
     }\r
 \r
     \r
@@ -172,13 +169,13 @@ UpdateVariableInfo (
       if (Entry->Next == NULL) {\r
         //\r
         // If the entry is not in the table add it.\r
-        // Next iteration of the loop will fill in the data\r
+        // Next iteration of the loop will fill in the data.\r
         //\r
         Entry->Next = AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY));\r
         ASSERT (Entry->Next != NULL);\r
 \r
         CopyGuid (&Entry->Next->VendorGuid, VendorGuid);\r
-        Entry->Next->Name = AllocatePool (StrLen (VariableName));\r
+        Entry->Next->Name = AllocatePool (StrSize (VariableName));\r
         ASSERT (Entry->Next->Name != NULL);\r
         StrCpy (Entry->Next->Name, VariableName);\r
         Entry->Next->Volatile = Volatile;\r
@@ -217,29 +214,29 @@ IsValidVariableHeader (
   This function writes data to the FWH at the correct LBA even if the LBAs\r
   are fragmented.\r
 \r
-  @param Global                  Pointer to VARAIBLE_GLOBAL structure\r
-  @param Volatile                Point out the Variable is Volatile or Non-Volatile\r
-  @param SetByIndex              TRUE if target pointer is given as index\r
-                                 FALSE if target pointer is absolute\r
-  @param Instance                Instance of FV Block services\r
+  @param Global                  Pointer to VARAIBLE_GLOBAL structure.\r
+  @param Volatile                Point out the Variable is Volatile or Non-Volatile.\r
+  @param SetByIndex              TRUE if target pointer is given as index.\r
+                                 FALSE if target pointer is absolute.\r
+  @param Fvb                     Pointer to the writable FVB protocol.\r
   @param DataPtrIndex            Pointer to the Data from the end of VARIABLE_STORE_HEADER\r
-                                 structure\r
-  @param DataSize                Size of data to be written\r
-  @param Buffer                  Pointer to the buffer from which data is written\r
+                                 structure.\r
+  @param DataSize                Size of data to be written.\r
+  @param Buffer                  Pointer to the buffer from which data is written.\r
 \r
-  @retval EFI_INVALID_PARAMETER  Parameters not valid\r
-  @retval EFI_SUCCESS            Variable store successfully updated\r
+  @retval EFI_INVALID_PARAMETER  Parameters not valid.\r
+  @retval EFI_SUCCESS            Variable store successfully updated.\r
 \r
 **/\r
 EFI_STATUS\r
 UpdateVariableStore (\r
-  IN  VARIABLE_GLOBAL         *Global,\r
-  IN  BOOLEAN                 Volatile,\r
-  IN  BOOLEAN                 SetByIndex,\r
-  IN  UINTN                   Instance,\r
-  IN  UINTN                   DataPtrIndex,\r
-  IN  UINT32                  DataSize,\r
-  IN  UINT8                   *Buffer\r
+  IN  VARIABLE_GLOBAL                     *Global,\r
+  IN  BOOLEAN                             Volatile,\r
+  IN  BOOLEAN                             SetByIndex,\r
+  IN  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL  *Fvb,\r
+  IN  UINTN                               DataPtrIndex,\r
+  IN  UINT32                              DataSize,\r
+  IN  UINT8                               *Buffer\r
   )\r
 {\r
   EFI_FV_BLOCK_MAP_ENTRY      *PtrBlockMapEntry;\r
@@ -260,14 +257,17 @@ UpdateVariableStore (
   DataPtr     = DataPtrIndex;\r
 \r
   //\r
-  // Check if the Data is Volatile\r
+  // Check if the Data is Volatile.\r
   //\r
   if (!Volatile) {\r
-    EfiFvbGetPhysicalAddress (Instance, &FvVolHdr);\r
+    ASSERT (Fvb != NULL);\r
+    Status = Fvb->GetPhysicalAddress(Fvb, &FvVolHdr);\r
+    ASSERT_EFI_ERROR (Status);\r
+\r
     FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *) ((UINTN) FvVolHdr);\r
     //\r
     // Data Pointer should point to the actual Address where data is to be\r
-    // written\r
+    // written.\r
     //\r
     if (SetByIndex) {\r
       DataPtr += mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;\r
@@ -279,7 +279,7 @@ UpdateVariableStore (
   } else {\r
     //\r
     // Data Pointer should point to the actual Address where data is to be\r
-    // written\r
+    // written.\r
     //\r
     VolatileBase = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);\r
     if (SetByIndex) {\r
@@ -298,7 +298,7 @@ UpdateVariableStore (
   }\r
   \r
   //\r
-  // If we are here we are dealing with Non-Volatile Variables\r
+  // If we are here we are dealing with Non-Volatile Variables.\r
   //\r
   LinearOffset  = (UINTN) FwVolHeader;\r
   CurrWritePtr  = (UINTN) DataPtr;\r
@@ -318,18 +318,18 @@ UpdateVariableStore (
       //\r
       if ((CurrWritePtr >= LinearOffset) && (CurrWritePtr < LinearOffset + PtrBlockMapEntry->Length)) {\r
         if ((CurrWritePtr + CurrWriteSize) <= (LinearOffset + PtrBlockMapEntry->Length)) {\r
-          Status = EfiFvbWriteBlock (\r
-                    Instance,\r
+          Status = Fvb->Write (\r
+                    Fvb,\r
                     LbaNumber,\r
                     (UINTN) (CurrWritePtr - LinearOffset),\r
                     &CurrWriteSize,\r
                     CurrBuffer\r
                     );\r
-            return Status;\r
+          return Status;\r
         } else {\r
           Size = (UINT32) (LinearOffset + PtrBlockMapEntry->Length - CurrWritePtr);\r
-          Status = EfiFvbWriteBlock (\r
-                    Instance,\r
+          Status = Fvb->Write (\r
+                    Fvb,\r
                     LbaNumber,\r
                     (UINTN) (CurrWritePtr - LinearOffset),\r
                     &Size,\r
@@ -360,9 +360,9 @@ UpdateVariableStore (
 \r
   @param VarStoreHeader  Pointer to the Variable Store Header.\r
 \r
-  @retval EfiRaw         Variable store status is raw\r
-  @retval EfiValid       Variable store status is valid\r
-  @retval EfiInvalid     Variable store status is invalid\r
+  @retval EfiRaw         Variable store status is raw.\r
+  @retval EfiValid       Variable store status is valid.\r
+  @retval EfiInvalid     Variable store status is invalid.\r
 \r
 **/\r
 VARIABLE_STORE_STATUS\r
@@ -370,16 +370,19 @@ GetVariableStoreStatus (
   IN VARIABLE_STORE_HEADER *VarStoreHeader\r
   )\r
 {\r
-  if (VarStoreHeader->Signature == VARIABLE_STORE_SIGNATURE &&\r
+  if (CompareGuid (&VarStoreHeader->Signature, &gEfiVariableGuid) &&\r
       VarStoreHeader->Format == VARIABLE_STORE_FORMATTED &&\r
       VarStoreHeader->State == VARIABLE_STORE_HEALTHY\r
       ) {\r
 \r
     return EfiValid;\r
-  } else if (VarStoreHeader->Signature == 0xffffffff &&\r
-           VarStoreHeader->Size == 0xffffffff &&\r
-           VarStoreHeader->Format == 0xff &&\r
-           VarStoreHeader->State == 0xff\r
+  } else if (((UINT32 *)(&VarStoreHeader->Signature))[0] == 0xffffffff &&\r
+             ((UINT32 *)(&VarStoreHeader->Signature))[1] == 0xffffffff &&\r
+             ((UINT32 *)(&VarStoreHeader->Signature))[2] == 0xffffffff &&\r
+             ((UINT32 *)(&VarStoreHeader->Signature))[3] == 0xffffffff &&\r
+             VarStoreHeader->Size == 0xffffffff &&\r
+             VarStoreHeader->Format == 0xff &&\r
+             VarStoreHeader->State == 0xff\r
           ) {\r
 \r
     return EfiRaw;\r
@@ -393,9 +396,9 @@ GetVariableStoreStatus (
 \r
   This code gets the size of name of variable.\r
 \r
-  @param Variable        Pointer to the Variable Header\r
+  @param Variable        Pointer to the Variable Header.\r
 \r
-  @return UINTN          Size of variable in bytes\r
+  @return UINTN          Size of variable in bytes.\r
 \r
 **/\r
 UINTN\r
@@ -416,9 +419,9 @@ NameSizeOfVariable (
 \r
   This code gets the size of variable data.\r
 \r
-  @param Variable        Pointer to the Variable Header\r
+  @param Variable        Pointer to the Variable Header.\r
 \r
-  @return Size of variable in bytes\r
+  @return Size of variable in bytes.\r
 \r
 **/\r
 UINTN\r
@@ -439,9 +442,9 @@ DataSizeOfVariable (
 \r
   This code gets the pointer to the variable name.\r
 \r
-  @param Variable        Pointer to the Variable Header\r
+  @param Variable        Pointer to the Variable Header.\r
 \r
-  @return Pointer to Variable Name which is Unicode encoding\r
+  @return Pointer to Variable Name which is Unicode encoding.\r
 \r
 **/\r
 CHAR16 *\r
@@ -457,9 +460,9 @@ GetVariableNamePtr (
 \r
   This code gets the pointer to the variable data.\r
 \r
-  @param Variable        Pointer to the Variable Header\r
+  @param Variable        Pointer to the Variable Header.\r
 \r
-  @return Pointer to Variable Data\r
+  @return Pointer to Variable Data.\r
 \r
 **/\r
 UINT8 *\r
@@ -470,7 +473,7 @@ GetVariableDataPtr (
   UINTN Value;\r
   \r
   //\r
-  // Be careful about pad size for alignment\r
+  // Be careful about pad size for alignment.\r
   //\r
   Value =  (UINTN) GetVariableNamePtr (Variable);\r
   Value += NameSizeOfVariable (Variable);\r
@@ -484,9 +487,9 @@ GetVariableDataPtr (
 \r
   This code gets the pointer to the next variable header.\r
 \r
-  @param Variable        Pointer to the Variable Header\r
+  @param Variable        Pointer to the Variable Header.\r
 \r
-  @return Pointer to next variable header\r
+  @return Pointer to next variable header.\r
 \r
 **/\r
 VARIABLE_HEADER *\r
@@ -505,7 +508,7 @@ GetNextVariablePtr (
   Value += GET_PAD_SIZE (DataSizeOfVariable (Variable));\r
 \r
   //\r
-  // Be careful about pad size for alignment\r
+  // Be careful about pad size for alignment.\r
   //\r
   return (VARIABLE_HEADER *) HEADER_ALIGN (Value);\r
 }\r
@@ -516,7 +519,7 @@ GetNextVariablePtr (
 \r
   @param VarStoreHeader  Pointer to the Variable Store Header.\r
 \r
-  @return Pointer to the first variable header\r
+  @return Pointer to the first variable header.\r
 \r
 **/\r
 VARIABLE_HEADER *\r
@@ -525,7 +528,7 @@ GetStartPointer (
   )\r
 {\r
   //\r
-  // The end of variable store\r
+  // The end of variable store.\r
   //\r
   return (VARIABLE_HEADER *) HEADER_ALIGN (VarStoreHeader + 1);\r
 }\r
@@ -537,9 +540,9 @@ GetStartPointer (
   This function gets pointer to the end of the variable storage\r
   area, according to the input variable store header.\r
 \r
-  @param VarStoreHeader  Pointer to the Variable Store Header\r
+  @param VarStoreHeader  Pointer to the Variable Store Header.\r
 \r
-  @return Pointer to the end of the variable storage area  \r
+  @return Pointer to the end of the variable storage area. \r
 \r
 **/\r
 VARIABLE_HEADER *\r
@@ -558,11 +561,13 @@ GetEndPointer (
 \r
   Variable store garbage collection and reclaim operation.\r
 \r
-  @param VariableBase            Base address of variable store\r
-  @param LastVariableOffset      Offset of last variable\r
-  @param IsVolatile              The variable store is volatile or not,\r
-                                 if it is non-volatile, need FTW\r
-  @param UpdatingVariable        Pointer to updateing variable.\r
+  @param VariableBase            Base address of variable store.\r
+  @param LastVariableOffset      Offset of last variable.\r
+  @param IsVolatile              The variable store is volatile or not;\r
+                                 if it is non-volatile, need FTW.\r
+  @param UpdatingPtrTrack        Pointer to updating variable pointer track structure.\r
+  @param NewVariable             Pointer to new variable.\r
+  @param NewVariableSize         New variable size.\r
 \r
   @return EFI_OUT_OF_RESOURCES\r
   @return EFI_SUCCESS\r
@@ -574,7 +579,9 @@ Reclaim (
   IN  EFI_PHYSICAL_ADDRESS  VariableBase,\r
   OUT UINTN                 *LastVariableOffset,\r
   IN  BOOLEAN               IsVolatile,\r
-  IN  VARIABLE_HEADER       *UpdatingVariable\r
+  IN OUT VARIABLE_POINTER_TRACK *UpdatingPtrTrack,\r
+  IN  VARIABLE_HEADER       *NewVariable,\r
+  IN  UINTN                 NewVariableSize\r
   )\r
 {\r
   VARIABLE_HEADER       *Variable;\r
@@ -585,103 +592,108 @@ Reclaim (
   UINT8                 *ValidBuffer;\r
   UINTN                 MaximumBufferSize;\r
   UINTN                 VariableSize;\r
-  UINTN                 VariableNameSize;\r
-  UINTN                 UpdatingVariableNameSize;\r
   UINTN                 NameSize;\r
   UINT8                 *CurrPtr;\r
   VOID                  *Point0;\r
   VOID                  *Point1;\r
   BOOLEAN               FoundAdded;\r
   EFI_STATUS            Status;\r
-  CHAR16                *VariableNamePtr;\r
-  CHAR16                *UpdatingVariableNamePtr;\r
+  UINTN                 CommonVariableTotalSize;\r
+  UINTN                 HwErrVariableTotalSize;\r
+  VARIABLE_HEADER       *UpdatingVariable;\r
+  VARIABLE_HEADER       *UpdatingInDeletedTransition;\r
+\r
+  UpdatingVariable = NULL;\r
+  UpdatingInDeletedTransition = NULL;\r
+  if (UpdatingPtrTrack != NULL) {\r
+    UpdatingVariable = UpdatingPtrTrack->CurrPtr;\r
+    UpdatingInDeletedTransition = UpdatingPtrTrack->InDeletedTransitionPtr;\r
+  }\r
 \r
   VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) VariableBase);\r
 \r
-  //\r
-  // Start Pointers for the variable.\r
-  //\r
-  Variable          = GetStartPointer (VariableStoreHeader);\r
-  MaximumBufferSize = sizeof (VARIABLE_STORE_HEADER);\r
+  CommonVariableTotalSize = 0;\r
+  HwErrVariableTotalSize  = 0;\r
 \r
-  while (IsValidVariableHeader (Variable)) {\r
-    NextVariable = GetNextVariablePtr (Variable);\r
-    if (Variable->State == VAR_ADDED || \r
-        Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)\r
-       ) {\r
-      VariableSize = (UINTN) NextVariable - (UINTN) Variable;\r
-      MaximumBufferSize += VariableSize;\r
+  if (IsVolatile) {\r
+    //\r
+    // Start Pointers for the variable.\r
+    //\r
+    Variable          = GetStartPointer (VariableStoreHeader);\r
+    MaximumBufferSize = sizeof (VARIABLE_STORE_HEADER);\r
+\r
+    while (IsValidVariableHeader (Variable)) {\r
+      NextVariable = GetNextVariablePtr (Variable);\r
+      if ((Variable->State == VAR_ADDED || Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) &&\r
+          Variable != UpdatingVariable &&\r
+          Variable != UpdatingInDeletedTransition\r
+         ) {\r
+        VariableSize = (UINTN) NextVariable - (UINTN) Variable;\r
+        MaximumBufferSize += VariableSize;\r
+      }\r
+\r
+      Variable = NextVariable;\r
     }\r
 \r
-    Variable = NextVariable;\r
-  }\r
+    if (NewVariable != NULL) {\r
+      //\r
+      // Add the new variable size.\r
+      //\r
+      MaximumBufferSize += NewVariableSize;\r
+    }\r
 \r
-  //\r
-  // Reserve the 1 Bytes with Oxff to identify the \r
-  // end of the variable buffer. \r
-  // \r
-  MaximumBufferSize += 1;\r
-  ValidBuffer = AllocatePool (MaximumBufferSize);\r
-  if (ValidBuffer == NULL) {\r
-    return EFI_OUT_OF_RESOURCES;\r
+    //\r
+    // Reserve the 1 Bytes with Oxff to identify the\r
+    // end of the variable buffer.\r
+    //\r
+    MaximumBufferSize += 1;\r
+    ValidBuffer = AllocatePool (MaximumBufferSize);\r
+    if (ValidBuffer == NULL) {\r
+      return EFI_OUT_OF_RESOURCES;\r
+    }\r
+  } else {\r
+    //\r
+    // For NV variable reclaim, don't allocate pool here and just use mNvVariableCache\r
+    // as the buffer to reduce SMRAM consumption for SMM variable driver.\r
+    //\r
+    MaximumBufferSize = mNvVariableCache->Size;\r
+    ValidBuffer = (UINT8 *) mNvVariableCache;\r
   }\r
 \r
   SetMem (ValidBuffer, MaximumBufferSize, 0xff);\r
 \r
   //\r
-  // Copy variable store header\r
+  // Copy variable store header.\r
   //\r
   CopyMem (ValidBuffer, VariableStoreHeader, sizeof (VARIABLE_STORE_HEADER));\r
   CurrPtr = (UINT8 *) GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer);\r
 \r
   //\r
-  // Reinstall all ADDED variables as long as they are not identical to Updating Variable\r
+  // Reinstall all ADDED variables as long as they are not identical to Updating Variable.\r
   // \r
   Variable = GetStartPointer (VariableStoreHeader);\r
   while (IsValidVariableHeader (Variable)) {\r
     NextVariable = GetNextVariablePtr (Variable);\r
-    if (Variable->State == VAR_ADDED) {\r
-      if (UpdatingVariable != NULL) {\r
-        if (UpdatingVariable == Variable) {\r
-          Variable = NextVariable;\r
-          continue;\r
-        }\r
-\r
-        VariableNameSize         = NameSizeOfVariable(Variable);\r
-        UpdatingVariableNameSize = NameSizeOfVariable(UpdatingVariable);\r
-\r
-        VariableNamePtr         = GetVariableNamePtr (Variable);\r
-        UpdatingVariableNamePtr = GetVariableNamePtr (UpdatingVariable);\r
-        if (CompareGuid (&Variable->VendorGuid, &UpdatingVariable->VendorGuid)    &&\r
-            VariableNameSize == UpdatingVariableNameSize &&\r
-            CompareMem (VariableNamePtr, UpdatingVariableNamePtr, VariableNameSize) == 0 ) {\r
-          Variable = NextVariable;\r
-          continue;\r
-        }\r
-      }\r
+    if (Variable != UpdatingVariable && Variable->State == VAR_ADDED) {\r
       VariableSize = (UINTN) NextVariable - (UINTN) Variable;\r
       CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize);\r
       CurrPtr += VariableSize;\r
+      if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {\r
+        HwErrVariableTotalSize += VariableSize;\r
+      } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {\r
+        CommonVariableTotalSize += VariableSize;\r
+      }\r
     }\r
     Variable = NextVariable;\r
   }\r
 \r
   //\r
-  // Reinstall the variable being updated if it is not NULL\r
-  //\r
-  if (UpdatingVariable != NULL) {\r
-    VariableSize = (UINTN)(GetNextVariablePtr (UpdatingVariable)) - (UINTN)UpdatingVariable;\r
-    CopyMem (CurrPtr, (UINT8 *) UpdatingVariable, VariableSize);\r
-    CurrPtr += VariableSize;\r
-  }\r
-\r
-  //\r
-  // Reinstall all in delete transition variables\r
+  // Reinstall all in delete transition variables.\r
   // \r
-  Variable      = GetStartPointer (VariableStoreHeader);\r
+  Variable = GetStartPointer (VariableStoreHeader);\r
   while (IsValidVariableHeader (Variable)) {\r
     NextVariable = GetNextVariablePtr (Variable);\r
-    if (Variable != UpdatingVariable && Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
+    if (Variable != UpdatingVariable && Variable != UpdatingInDeletedTransition && Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
 \r
       //\r
       // Buffer has cached all ADDED variable. \r
@@ -699,7 +711,7 @@ Reclaim (
            ) {\r
           Point0 = (VOID *) GetVariableNamePtr (AddedVariable);\r
           Point1 = (VOID *) GetVariableNamePtr (Variable);\r
-          if (CompareMem (Point0, Point1, NameSizeOfVariable (AddedVariable)) == 0) {\r
+          if (CompareMem (Point0, Point1, NameSize) == 0) {\r
             FoundAdded = TRUE;\r
             break;\r
           }\r
@@ -708,181 +720,201 @@ Reclaim (
       }\r
       if (!FoundAdded) {\r
         //\r
-        // Promote VAR_IN_DELETED_TRANSITION to VAR_ADDED\r
+        // Promote VAR_IN_DELETED_TRANSITION to VAR_ADDED.\r
         //\r
         VariableSize = (UINTN) NextVariable - (UINTN) Variable;\r
         CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize);\r
         ((VARIABLE_HEADER *) CurrPtr)->State = VAR_ADDED;\r
         CurrPtr += VariableSize;\r
+        if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {\r
+          HwErrVariableTotalSize += VariableSize;\r
+        } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {\r
+          CommonVariableTotalSize += VariableSize;\r
+        }\r
       }\r
     }\r
 \r
     Variable = NextVariable;\r
   }\r
 \r
+  //\r
+  // Install the new variable if it is not NULL.\r
+  //\r
+  if (NewVariable != NULL) {\r
+    if ((UINTN) (CurrPtr - ValidBuffer) + NewVariableSize > VariableStoreHeader->Size) {\r
+      //\r
+      // No enough space to store the new variable.\r
+      //\r
+      Status = EFI_OUT_OF_RESOURCES;\r
+      goto Done;\r
+    }\r
+    if (!IsVolatile) {\r
+      if ((NewVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+        HwErrVariableTotalSize += NewVariableSize;\r
+      } else if ((NewVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+        CommonVariableTotalSize += NewVariableSize;\r
+      }\r
+      if ((HwErrVariableTotalSize > PcdGet32 (PcdHwErrStorageSize)) ||\r
+          (CommonVariableTotalSize > VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize))) {\r
+        //\r
+        // No enough space to store the new variable by NV or NV+HR attribute.\r
+        //\r
+        Status = EFI_OUT_OF_RESOURCES;\r
+        goto Done;\r
+      }\r
+    }\r
+\r
+    CopyMem (CurrPtr, (UINT8 *) NewVariable, NewVariableSize);\r
+    ((VARIABLE_HEADER *) CurrPtr)->State = VAR_ADDED;\r
+    if (UpdatingVariable != NULL) {\r
+      UpdatingPtrTrack->CurrPtr = (VARIABLE_HEADER *)((UINTN)UpdatingPtrTrack->StartPtr + ((UINTN)CurrPtr - (UINTN)GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer)));\r
+      UpdatingPtrTrack->InDeletedTransitionPtr = NULL;\r
+    }\r
+    CurrPtr += NewVariableSize;\r
+  }\r
+\r
   if (IsVolatile) {\r
     //\r
-    // If volatile variable store, just copy valid buffer\r
+    // If volatile variable store, just copy valid buffer.\r
     //\r
     SetMem ((UINT8 *) (UINTN) VariableBase, VariableStoreHeader->Size, 0xff);\r
-    CopyMem ((UINT8 *) (UINTN) VariableBase, ValidBuffer, (UINTN) (CurrPtr - (UINT8 *) ValidBuffer));\r
-    Status              = EFI_SUCCESS;\r
+    CopyMem ((UINT8 *) (UINTN) VariableBase, ValidBuffer, (UINTN) (CurrPtr - ValidBuffer));\r
+    *LastVariableOffset = (UINTN) (CurrPtr - ValidBuffer);\r
+    Status  = EFI_SUCCESS;\r
   } else {\r
     //\r
     // If non-volatile variable store, perform FTW here.\r
     //\r
     Status = FtwVariableSpace (\r
               VariableBase,\r
-              ValidBuffer,\r
-              (UINTN) (CurrPtr - (UINT8 *) ValidBuffer)\r
+              (VARIABLE_STORE_HEADER *) ValidBuffer\r
               );\r
+    if (!EFI_ERROR (Status)) {\r
+      *LastVariableOffset = (UINTN) (CurrPtr - ValidBuffer);\r
+      mVariableModuleGlobal->HwErrVariableTotalSize = HwErrVariableTotalSize;\r
+      mVariableModuleGlobal->CommonVariableTotalSize = CommonVariableTotalSize;\r
+    } else {\r
+      NextVariable  = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableBase);\r
+      while (IsValidVariableHeader (NextVariable)) {\r
+        VariableSize = NextVariable->NameSize + NextVariable->DataSize + sizeof (VARIABLE_HEADER);\r
+        if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+          mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VariableSize);\r
+        } else if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+          mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VariableSize);\r
+        }\r
+\r
+        NextVariable = GetNextVariablePtr (NextVariable);\r
+      }\r
+      *LastVariableOffset = (UINTN) NextVariable - (UINTN) VariableBase;\r
+    }\r
   }\r
-  if (!EFI_ERROR (Status)) {\r
-    *LastVariableOffset = (UINTN) (CurrPtr - (UINT8 *) ValidBuffer);\r
+\r
+Done:\r
+  if (IsVolatile) {\r
+    FreePool (ValidBuffer);\r
   } else {\r
-    *LastVariableOffset = 0;\r
+    //\r
+    // For NV variable reclaim, we use mNvVariableCache as the buffer, so copy the data back.\r
+    //\r
+    CopyMem (mNvVariableCache, (UINT8 *)(UINTN)VariableBase, VariableStoreHeader->Size);\r
   }\r
 \r
-  FreePool (ValidBuffer);\r
-\r
   return Status;\r
 }\r
 \r
-\r
-/**\r
-  Update the Cache with Variable information. These are the same \r
-  arguments as the EFI Variable services.\r
-\r
-  @param[in] VariableName  Name of variable\r
-  @param[in] VendorGuid    Guid of variable\r
-  @param[in] Attributes    Attribues of the variable\r
-  @param[in] DataSize      Size of data. 0 means delete\r
-  @param[in] Data          Variable data\r
-\r
-**/\r
-VOID\r
-UpdateVariableCache (\r
-  IN      CHAR16            *VariableName,\r
-  IN      EFI_GUID          *VendorGuid,\r
-  IN      UINT32            Attributes,\r
-  IN      UINTN             DataSize,\r
-  IN      VOID              *Data\r
-  )\r
-{\r
-  VARIABLE_CACHE_ENTRY      *Entry;\r
-  UINTN                     Index;\r
-\r
-  if (EfiAtRuntime ()) {\r
-    // Don't use the cache at runtime\r
-    return;\r
-  }\r
-\r
-  for (Index = 0, Entry = mVariableCache; Index < sizeof (mVariableCache)/sizeof (VARIABLE_CACHE_ENTRY); Index++, Entry++) {\r
-    if (CompareGuid (VendorGuid, Entry->Guid)) {\r
-      if (StrCmp (VariableName, Entry->Name) == 0) { \r
-        Entry->Attributes = Attributes;\r
-        if (DataSize == 0) {\r
-          // Delete Case\r
-          if (Entry->DataSize != 0) {\r
-            FreePool (Entry->Data);\r
-          }\r
-          Entry->DataSize = DataSize;\r
-        } else if (DataSize == Entry->DataSize) {\r
-          CopyMem (Entry->Data, Data, DataSize);\r
-        } else {\r
-          Entry->Data = AllocatePool (DataSize);\r
-          Entry->DataSize = DataSize;\r
-          CopyMem (Entry->Data, Data, DataSize);\r
-        }\r
-      }\r
-    }\r
-  }\r
-}\r
-\r
-\r
 /**\r
-  Search the cache to check if the variable is in it.\r
-\r
-  This function searches the variable cache. If the variable to find exists, return its data\r
-  and attributes.\r
-\r
-  @param  VariableName          A Null-terminated Unicode string that is the name of the vendor's\r
-                                variable.  Each VariableName is unique for each \r
-                                VendorGuid.\r
-  @param  VendorGuid            A unique identifier for the vendor\r
-  @param  Attributes            Pointer to the attributes bitmask of the variable for output.\r
-  @param  DataSize              On input, size of the buffer of Data.\r
-                                On output, size of the variable's data.\r
-  @param  Data                  Pointer to the data buffer for output.\r
+  Find the variable in the specified variable store.\r
 \r
-  @retval EFI_SUCCESS           VariableGuid & VariableName data was returned.\r
-  @retval EFI_NOT_FOUND         No matching variable found in cache.\r
-  @retval EFI_BUFFER_TOO_SMALL  *DataSize is smaller than size of the variable's data to return.\r
+  @param  VariableName        Name of the variable to be found\r
+  @param  VendorGuid          Vendor GUID to be found.\r
+  @param  IgnoreRtCheck       Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute\r
+                              check at runtime when searching variable.\r
+  @param  PtrTrack            Variable Track Pointer structure that contains Variable Information.\r
 \r
+  @retval  EFI_SUCCESS            Variable found successfully\r
+  @retval  EFI_NOT_FOUND          Variable not found\r
 **/\r
 EFI_STATUS\r
-FindVariableInCache (\r
-  IN      CHAR16            *VariableName,\r
-  IN      EFI_GUID          *VendorGuid,\r
-  OUT     UINT32            *Attributes OPTIONAL,\r
-  IN OUT  UINTN             *DataSize,\r
-  OUT     VOID              *Data\r
+FindVariableEx (\r
+  IN     CHAR16                  *VariableName,\r
+  IN     EFI_GUID                *VendorGuid,\r
+  IN     BOOLEAN                 IgnoreRtCheck,\r
+  IN OUT VARIABLE_POINTER_TRACK  *PtrTrack\r
   )\r
 {\r
-  VARIABLE_CACHE_ENTRY      *Entry;\r
-  UINTN                     Index;\r
+  VARIABLE_HEADER                *InDeletedVariable;\r
+  VOID                           *Point;\r
 \r
-  if (EfiAtRuntime ()) {\r
-    // Don't use the cache at runtime\r
-    return EFI_NOT_FOUND;\r
-  }\r
+  PtrTrack->InDeletedTransitionPtr = NULL;\r
+\r
+  //\r
+  // Find the variable by walk through HOB, volatile and non-volatile variable store.\r
+  //\r
+  InDeletedVariable  = NULL;\r
 \r
-  for (Index = 0, Entry = mVariableCache; Index < sizeof (mVariableCache)/sizeof (VARIABLE_CACHE_ENTRY); Index++, Entry++) {\r
-    if (CompareGuid (VendorGuid, Entry->Guid)) {\r
-      if (StrCmp (VariableName, Entry->Name) == 0) {\r
-        if (Entry->DataSize == 0) {\r
-          // Variable was deleted so return not found\r
-          return EFI_NOT_FOUND;\r
-        } else if (Entry->DataSize > *DataSize) {\r
-          // If the buffer is too small return correct size\r
-          *DataSize = Entry->DataSize;\r
-          return EFI_BUFFER_TOO_SMALL;\r
+  for ( PtrTrack->CurrPtr = PtrTrack->StartPtr\r
+      ; (PtrTrack->CurrPtr < PtrTrack->EndPtr) && IsValidVariableHeader (PtrTrack->CurrPtr)\r
+      ; PtrTrack->CurrPtr = GetNextVariablePtr (PtrTrack->CurrPtr)\r
+      ) {\r
+    if (PtrTrack->CurrPtr->State == VAR_ADDED || \r
+        PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)\r
+       ) {\r
+      if (IgnoreRtCheck || !AtRuntime () || ((PtrTrack->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {\r
+        if (VariableName[0] == 0) {\r
+          if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
+            InDeletedVariable   = PtrTrack->CurrPtr;\r
+          } else {\r
+            PtrTrack->InDeletedTransitionPtr = InDeletedVariable;\r
+            return EFI_SUCCESS;\r
+          }\r
         } else {\r
-          *DataSize = Entry->DataSize;\r
-          // Return the data\r
-          CopyMem (Data, Entry->Data, Entry->DataSize);\r
-          if (Attributes != NULL) {\r
-            *Attributes = Entry->Attributes;\r
+          if (CompareGuid (VendorGuid, &PtrTrack->CurrPtr->VendorGuid)) {\r
+            Point = (VOID *) GetVariableNamePtr (PtrTrack->CurrPtr);\r
+\r
+            ASSERT (NameSizeOfVariable (PtrTrack->CurrPtr) != 0);\r
+            if (CompareMem (VariableName, Point, NameSizeOfVariable (PtrTrack->CurrPtr)) == 0) {\r
+              if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
+                InDeletedVariable     = PtrTrack->CurrPtr;\r
+              } else {\r
+                PtrTrack->InDeletedTransitionPtr = InDeletedVariable;\r
+                return EFI_SUCCESS;\r
+              }\r
+            }\r
           }\r
-          return EFI_SUCCESS;\r
         }\r
       }\r
     }\r
   }\r
-  \r
-  return EFI_NOT_FOUND;\r
+\r
+  PtrTrack->CurrPtr = InDeletedVariable;\r
+  return (PtrTrack->CurrPtr  == NULL) ? EFI_NOT_FOUND : EFI_SUCCESS;\r
 }\r
 \r
+\r
 /**\r
   Finds variable in storage blocks of volatile and non-volatile storage areas.\r
 \r
   This code finds variable in storage blocks of volatile and non-volatile storage areas.\r
   If VariableName is an empty string, then we just return the first\r
   qualified variable without comparing VariableName and VendorGuid.\r
-  Otherwise, VariableName and VendorGuid are compared.\r
+  If IgnoreRtCheck is TRUE, then we ignore the EFI_VARIABLE_RUNTIME_ACCESS attribute check\r
+  at runtime when searching existing variable, only VariableName and VendorGuid are compared.\r
+  Otherwise, variables without EFI_VARIABLE_RUNTIME_ACCESS are not visible at runtime.\r
 \r
-  @param  VariableName                Name of the variable to be found\r
+  @param  VariableName                Name of the variable to be found.\r
   @param  VendorGuid                  Vendor GUID to be found.\r
   @param  PtrTrack                    VARIABLE_POINTER_TRACK structure for output,\r
                                       including the range searched and the target position.\r
   @param  Global                      Pointer to VARIABLE_GLOBAL structure, including\r
                                       base of volatile variable storage area, base of\r
                                       NV variable storage area, and a lock.\r
+  @param  IgnoreRtCheck               Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute\r
+                                      check at runtime when searching variable.\r
 \r
   @retval EFI_INVALID_PARAMETER       If VariableName is not an empty string, while\r
-                                      VendorGuid is NULL\r
-  @retval EFI_SUCCESS                 Variable successfully found\r
-  @retval EFI_INVALID_PARAMETER       Variable not found\r
+                                      VendorGuid is NULL.\r
+  @retval EFI_SUCCESS                 Variable successfully found.\r
+  @retval EFI_NOT_FOUND               Variable not found\r
 \r
 **/\r
 EFI_STATUS\r
@@ -890,478 +922,905 @@ FindVariable (
   IN  CHAR16                  *VariableName,\r
   IN  EFI_GUID                *VendorGuid,\r
   OUT VARIABLE_POINTER_TRACK  *PtrTrack,\r
-  IN  VARIABLE_GLOBAL         *Global\r
+  IN  VARIABLE_GLOBAL         *Global,\r
+  IN  BOOLEAN                 IgnoreRtCheck\r
   )\r
 {\r
-  VARIABLE_HEADER         *Variable[2];\r
-  VARIABLE_HEADER         *InDeletedVariable;\r
-  VARIABLE_STORE_HEADER   *VariableStoreHeader[2];\r
-  UINTN                   InDeletedStorageIndex;\r
-  UINTN                   Index;\r
-  VOID                    *Point;\r
+  EFI_STATUS              Status;\r
+  VARIABLE_STORE_HEADER   *VariableStoreHeader[VariableStoreTypeMax];\r
+  VARIABLE_STORE_TYPE     Type;\r
+\r
+  if (VariableName[0] != 0 && VendorGuid == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
 \r
   //\r
-  // 0: Volatile, 1: Non-Volatile\r
+  // 0: Volatile, 1: HOB, 2: Non-Volatile.\r
   // The index and attributes mapping must be kept in this order as RuntimeServiceGetNextVariableName\r
-  // make use of this mapping to implement search algorithme.\r
+  // make use of this mapping to implement search algorithm.\r
   //\r
-  VariableStoreHeader[0]  = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);\r
-  VariableStoreHeader[1]  = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase);\r
+  VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) Global->VolatileVariableBase;\r
+  VariableStoreHeader[VariableStoreTypeHob]      = (VARIABLE_STORE_HEADER *) (UINTN) Global->HobVariableBase;\r
+  VariableStoreHeader[VariableStoreTypeNv]       = mNvVariableCache;\r
 \r
   //\r
-  // Start Pointers for the variable.\r
-  // Actual Data Pointer where data can be written.\r
+  // Find the variable by walk through HOB, volatile and non-volatile variable store.\r
   //\r
-  Variable[0] = GetStartPointer (VariableStoreHeader[0]);\r
-  Variable[1] = GetStartPointer (VariableStoreHeader[1]);\r
+  for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {\r
+    if (VariableStoreHeader[Type] == NULL) {\r
+      continue;\r
+    }\r
 \r
-  if (VariableName[0] != 0 && VendorGuid == NULL) {\r
-    return EFI_INVALID_PARAMETER;\r
+    PtrTrack->StartPtr = GetStartPointer (VariableStoreHeader[Type]);\r
+    PtrTrack->EndPtr   = GetEndPointer   (VariableStoreHeader[Type]);\r
+    PtrTrack->Volatile = (BOOLEAN) (Type == VariableStoreTypeVolatile);\r
+\r
+    Status = FindVariableEx (VariableName, VendorGuid, IgnoreRtCheck, PtrTrack);\r
+    if (!EFI_ERROR (Status)) {\r
+      return Status;\r
+    }\r
   }\r
+  return EFI_NOT_FOUND;\r
+}\r
 \r
-  //\r
-  // Find the variable by walk through volatile and then non-volatile variable store\r
-  //\r
-  InDeletedVariable     = NULL;\r
-  InDeletedStorageIndex = 0;\r
-  for (Index = 0; Index < 2; Index++) {\r
-    while (IsValidVariableHeader (Variable[Index]) && (Variable[Index] <= GetEndPointer (VariableStoreHeader[Index]))) {\r
-      if (Variable[Index]->State == VAR_ADDED || \r
-          Variable[Index]->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)\r
-         ) {\r
-        if (!EfiAtRuntime () || (Variable[Index]->Attributes & EFI_VARIABLE_RUNTIME_ACCESS)) {\r
-          if (VariableName[0] == 0) {\r
-            if (Variable[Index]->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
-              InDeletedVariable     = Variable[Index];\r
-              InDeletedStorageIndex = Index;\r
-            } else {\r
-              PtrTrack->StartPtr  = GetStartPointer (VariableStoreHeader[Index]);\r
-              PtrTrack->EndPtr    = GetEndPointer (VariableStoreHeader[Index]);\r
-              PtrTrack->CurrPtr   = Variable[Index];\r
-              PtrTrack->Volatile  = (BOOLEAN)(Index == 0);\r
-\r
-              return EFI_SUCCESS;\r
-            }\r
-          } else {\r
-            if (CompareGuid (VendorGuid, &Variable[Index]->VendorGuid)) {\r
-              Point = (VOID *) GetVariableNamePtr (Variable[Index]);\r
-\r
-              ASSERT (NameSizeOfVariable (Variable[Index]) != 0);\r
-              if (!CompareMem (VariableName, Point, NameSizeOfVariable (Variable[Index]))) {\r
-                if (Variable[Index]->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
-                  InDeletedVariable     = Variable[Index];\r
-                  InDeletedStorageIndex = Index;\r
-                } else {\r
-                  PtrTrack->StartPtr  = GetStartPointer (VariableStoreHeader[Index]);\r
-                  PtrTrack->EndPtr    = GetEndPointer (VariableStoreHeader[Index]);\r
-                  PtrTrack->CurrPtr   = Variable[Index];\r
-                  PtrTrack->Volatile  = (BOOLEAN)(Index == 0);\r
-\r
-                  return EFI_SUCCESS;\r
-                }\r
-              }\r
-            }\r
-          }\r
-        }\r
-      }\r
+/**\r
+  Get index from supported language codes according to language string.\r
+\r
+  This code is used to get corresponding index in supported language codes. It can handle\r
+  RFC4646 and ISO639 language tags.\r
+  In ISO639 language tags, take 3-characters as a delimitation to find matched string and calculate the index.\r
+  In RFC4646 language tags, take semicolon as a delimitation to find matched string and calculate the index.\r
+\r
+  For example:\r
+    SupportedLang  = "engfraengfra"\r
+    Lang           = "eng"\r
+    Iso639Language = TRUE\r
+  The return value is "0".\r
+  Another example:\r
+    SupportedLang  = "en;fr;en-US;fr-FR"\r
+    Lang           = "fr-FR"\r
+    Iso639Language = FALSE\r
+  The return value is "3".\r
+\r
+  @param  SupportedLang               Platform supported language codes.\r
+  @param  Lang                        Configured language.\r
+  @param  Iso639Language              A bool value to signify if the handler is operated on ISO639 or RFC4646.\r
+\r
+  @retval The index of language in the language codes.\r
 \r
-      Variable[Index] = GetNextVariablePtr (Variable[Index]);\r
+**/\r
+UINTN\r
+GetIndexFromSupportedLangCodes(\r
+  IN  CHAR8            *SupportedLang,\r
+  IN  CHAR8            *Lang,\r
+  IN  BOOLEAN          Iso639Language\r
+  ) \r
+{\r
+  UINTN    Index;\r
+  UINTN    CompareLength;\r
+  UINTN    LanguageLength;\r
+\r
+  if (Iso639Language) {\r
+    CompareLength = ISO_639_2_ENTRY_SIZE;\r
+    for (Index = 0; Index < AsciiStrLen (SupportedLang); Index += CompareLength) {\r
+      if (AsciiStrnCmp (Lang, SupportedLang + Index, CompareLength) == 0) {\r
+        //\r
+        // Successfully find the index of Lang string in SupportedLang string.\r
+        //\r
+        Index = Index / CompareLength;\r
+        return Index;\r
+      }\r
     }\r
-    if (InDeletedVariable != NULL) {\r
-      PtrTrack->StartPtr  = GetStartPointer (VariableStoreHeader[InDeletedStorageIndex]);\r
-      PtrTrack->EndPtr    = GetEndPointer (VariableStoreHeader[InDeletedStorageIndex]);\r
-      PtrTrack->CurrPtr   = InDeletedVariable;\r
-      PtrTrack->Volatile  = (BOOLEAN)(InDeletedStorageIndex == 0);\r
-      return EFI_SUCCESS;\r
+    ASSERT (FALSE);\r
+    return 0;\r
+  } else {\r
+    //\r
+    // Compare RFC4646 language code\r
+    //\r
+    Index = 0;\r
+    for (LanguageLength = 0; Lang[LanguageLength] != '\0'; LanguageLength++);\r
+\r
+    for (Index = 0; *SupportedLang != '\0'; Index++, SupportedLang += CompareLength) {\r
+      //\r
+      // Skip ';' characters in SupportedLang\r
+      //\r
+      for (; *SupportedLang != '\0' && *SupportedLang == ';'; SupportedLang++);\r
+      //\r
+      // Determine the length of the next language code in SupportedLang\r
+      //\r
+      for (CompareLength = 0; SupportedLang[CompareLength] != '\0' && SupportedLang[CompareLength] != ';'; CompareLength++);\r
+      \r
+      if ((CompareLength == LanguageLength) && \r
+          (AsciiStrnCmp (Lang, SupportedLang, CompareLength) == 0)) {\r
+        //\r
+        // Successfully find the index of Lang string in SupportedLang string.\r
+        //\r
+        return Index;\r
+      }\r
     }\r
+    ASSERT (FALSE);\r
+    return 0;\r
   }\r
-  PtrTrack->CurrPtr = NULL;\r
-  return EFI_NOT_FOUND;\r
 }\r
 \r
-\r
 /**\r
+  Get language string from supported language codes according to index.\r
+\r
+  This code is used to get corresponding language strings in supported language codes. It can handle\r
+  RFC4646 and ISO639 language tags.\r
+  In ISO639 language tags, take 3-characters as a delimitation. Find language string according to the index.\r
+  In RFC4646 language tags, take semicolon as a delimitation. Find language string according to the index.\r
+\r
+  For example:\r
+    SupportedLang  = "engfraengfra"\r
+    Index          = "1"\r
+    Iso639Language = TRUE\r
+  The return value is "fra".\r
+  Another example:\r
+    SupportedLang  = "en;fr;en-US;fr-FR"\r
+    Index          = "1"\r
+    Iso639Language = FALSE\r
+  The return value is "fr".\r
+\r
+  @param  SupportedLang               Platform supported language codes.\r
+  @param  Index                       The index in supported language codes.\r
+  @param  Iso639Language              A bool value to signify if the handler is operated on ISO639 or RFC4646.\r
+\r
+  @retval The language string in the language codes.\r
 \r
-  This code finds variable in storage blocks (Volatile or Non-Volatile).\r
+**/\r
+CHAR8 *\r
+GetLangFromSupportedLangCodes (\r
+  IN  CHAR8            *SupportedLang,\r
+  IN  UINTN            Index,\r
+  IN  BOOLEAN          Iso639Language\r
+)\r
+{\r
+  UINTN    SubIndex;\r
+  UINTN    CompareLength;\r
+  CHAR8    *Supported;\r
 \r
-  @param VariableName               Name of Variable to be found.\r
-  @param VendorGuid                 Variable vendor GUID.\r
-  @param Attributes                 Attribute value of the variable found.\r
-  @param DataSize                   Size of Data found. If size is less than the\r
-                                    data, this value contains the required size.\r
-  @param Data                       Data pointer.\r
-                      \r
-  @return EFI_INVALID_PARAMETER     Invalid parameter\r
-  @return EFI_SUCCESS               Find the specified variable\r
-  @return EFI_NOT_FOUND             Not found\r
-  @return EFI_BUFFER_TO_SMALL       DataSize is too small for the result\r
+  SubIndex  = 0;\r
+  Supported = SupportedLang;\r
+  if (Iso639Language) {\r
+    //\r
+    // According to the index of Lang string in SupportedLang string to get the language.\r
+    // This code will be invoked in RUNTIME, therefore there is not a memory allocate/free operation.\r
+    // In driver entry, it pre-allocates a runtime attribute memory to accommodate this string.\r
+    //\r
+    CompareLength = ISO_639_2_ENTRY_SIZE;\r
+    mVariableModuleGlobal->Lang[CompareLength] = '\0';\r
+    return CopyMem (mVariableModuleGlobal->Lang, SupportedLang + Index * CompareLength, CompareLength);\r
+\r
+  } else {\r
+    while (TRUE) {\r
+      //\r
+      // Take semicolon as delimitation, sequentially traverse supported language codes.\r
+      //\r
+      for (CompareLength = 0; *Supported != ';' && *Supported != '\0'; CompareLength++) {\r
+        Supported++;\r
+      }\r
+      if ((*Supported == '\0') && (SubIndex != Index)) {\r
+        //\r
+        // Have completed the traverse, but not find corrsponding string.\r
+        // This case is not allowed to happen.\r
+        //\r
+        ASSERT(FALSE);\r
+        return NULL;\r
+      }\r
+      if (SubIndex == Index) {\r
+        //\r
+        // According to the index of Lang string in SupportedLang string to get the language.\r
+        // As this code will be invoked in RUNTIME, therefore there is not memory allocate/free operation.\r
+        // In driver entry, it pre-allocates a runtime attribute memory to accommodate this string.\r
+        //\r
+        mVariableModuleGlobal->PlatformLang[CompareLength] = '\0';\r
+        return CopyMem (mVariableModuleGlobal->PlatformLang, Supported - CompareLength, CompareLength);\r
+      }\r
+      SubIndex++;\r
+\r
+      //\r
+      // Skip ';' characters in Supported\r
+      //\r
+      for (; *Supported != '\0' && *Supported == ';'; Supported++);\r
+    }\r
+  }\r
+}\r
+\r
+/**\r
+  Returns a pointer to an allocated buffer that contains the best matching language \r
+  from a set of supported languages.  \r
+  \r
+  This function supports both ISO 639-2 and RFC 4646 language codes, but language \r
+  code types may not be mixed in a single call to this function. This function\r
+  supports a variable argument list that allows the caller to pass in a prioritized\r
+  list of language codes to test against all the language codes in SupportedLanguages.\r
+\r
+  If SupportedLanguages is NULL, then ASSERT().\r
+\r
+  @param[in]  SupportedLanguages  A pointer to a Null-terminated ASCII string that\r
+                                  contains a set of language codes in the format \r
+                                  specified by Iso639Language.\r
+  @param[in]  Iso639Language      If TRUE, then all language codes are assumed to be\r
+                                  in ISO 639-2 format.  If FALSE, then all language\r
+                                  codes are assumed to be in RFC 4646 language format\r
+  @param[in]  ...                 A variable argument list that contains pointers to \r
+                                  Null-terminated ASCII strings that contain one or more\r
+                                  language codes in the format specified by Iso639Language.\r
+                                  The first language code from each of these language\r
+                                  code lists is used to determine if it is an exact or\r
+                                  close match to any of the language codes in \r
+                                  SupportedLanguages.  Close matches only apply to RFC 4646\r
+                                  language codes, and the matching algorithm from RFC 4647\r
+                                  is used to determine if a close match is present.  If \r
+                                  an exact or close match is found, then the matching\r
+                                  language code from SupportedLanguages is returned.  If\r
+                                  no matches are found, then the next variable argument\r
+                                  parameter is evaluated.  The variable argument list \r
+                                  is terminated by a NULL.\r
+\r
+  @retval NULL   The best matching language could not be found in SupportedLanguages.\r
+  @retval NULL   There are not enough resources available to return the best matching \r
+                 language.\r
+  @retval Other  A pointer to a Null-terminated ASCII string that is the best matching \r
+                 language in SupportedLanguages.\r
 \r
 **/\r
-EFI_STATUS\r
+CHAR8 *\r
 EFIAPI\r
-RuntimeServiceGetVariable (\r
-  IN      CHAR16            *VariableName,\r
-  IN      EFI_GUID          *VendorGuid,\r
-  OUT     UINT32            *Attributes OPTIONAL,\r
-  IN OUT  UINTN             *DataSize,\r
-  OUT     VOID              *Data\r
+VariableGetBestLanguage (\r
+  IN CONST CHAR8  *SupportedLanguages, \r
+  IN BOOLEAN      Iso639Language,\r
+  ...\r
   )\r
 {\r
-  EFI_STATUS              Status;\r
-  VARIABLE_POINTER_TRACK  Variable;\r
-  UINTN                   VarDataSize;\r
+  VA_LIST      Args;\r
+  CHAR8        *Language;\r
+  UINTN        CompareLength;\r
+  UINTN        LanguageLength;\r
+  CONST CHAR8  *Supported;\r
+  CHAR8        *Buffer;\r
 \r
-  if (VariableName == NULL || VendorGuid == NULL || DataSize == NULL) {\r
-    return EFI_INVALID_PARAMETER;\r
-  }\r
+  ASSERT (SupportedLanguages != NULL);\r
 \r
-  AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
+  VA_START (Args, Iso639Language);\r
+  while ((Language = VA_ARG (Args, CHAR8 *)) != NULL) {\r
+    //\r
+    // Default to ISO 639-2 mode\r
+    //\r
+    CompareLength  = 3;\r
+    LanguageLength = MIN (3, AsciiStrLen (Language));\r
 \r
-  //\r
-  // Find existing variable\r
-  //\r
-  Status = FindVariableInCache (VariableName, VendorGuid, Attributes, DataSize, Data);\r
-  if ((Status == EFI_BUFFER_TOO_SMALL) || (Status == EFI_SUCCESS)){\r
-    // Hit in the Cache\r
-    UpdateVariableInfo (VariableName, VendorGuid, FALSE, TRUE, FALSE, FALSE, TRUE);\r
-    goto Done;\r
-  }\r
-  \r
-  Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal);\r
-  if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {\r
-    goto Done;\r
+    //\r
+    // If in RFC 4646 mode, then determine the length of the first RFC 4646 language code in Language\r
+    //\r
+    if (!Iso639Language) {\r
+      for (LanguageLength = 0; Language[LanguageLength] != 0 && Language[LanguageLength] != ';'; LanguageLength++);\r
+    }\r
+\r
+    //\r
+    // Trim back the length of Language used until it is empty\r
+    //\r
+    while (LanguageLength > 0) {\r
+      //\r
+      // Loop through all language codes in SupportedLanguages\r
+      //\r
+      for (Supported = SupportedLanguages; *Supported != '\0'; Supported += CompareLength) {\r
+        //\r
+        // In RFC 4646 mode, then Loop through all language codes in SupportedLanguages\r
+        //\r
+        if (!Iso639Language) {\r
+          //\r
+          // Skip ';' characters in Supported\r
+          //\r
+          for (; *Supported != '\0' && *Supported == ';'; Supported++);\r
+          //\r
+          // Determine the length of the next language code in Supported\r
+          //\r
+          for (CompareLength = 0; Supported[CompareLength] != 0 && Supported[CompareLength] != ';'; CompareLength++);\r
+          //\r
+          // If Language is longer than the Supported, then skip to the next language\r
+          //\r
+          if (LanguageLength > CompareLength) {\r
+            continue;\r
+          }\r
+        }\r
+        //\r
+        // See if the first LanguageLength characters in Supported match Language\r
+        //\r
+        if (AsciiStrnCmp (Supported, Language, LanguageLength) == 0) {\r
+          VA_END (Args);\r
+\r
+          Buffer = Iso639Language ? mVariableModuleGlobal->Lang : mVariableModuleGlobal->PlatformLang;\r
+          Buffer[CompareLength] = '\0';\r
+          return CopyMem (Buffer, Supported, CompareLength);\r
+        }\r
+      }\r
+\r
+      if (Iso639Language) {\r
+        //\r
+        // If ISO 639 mode, then each language can only be tested once\r
+        //\r
+        LanguageLength = 0;\r
+      } else {\r
+        //\r
+        // If RFC 4646 mode, then trim Language from the right to the next '-' character \r
+        //\r
+        for (LanguageLength--; LanguageLength > 0 && Language[LanguageLength] != '-'; LanguageLength--);\r
+      }\r
+    }\r
   }\r
+  VA_END (Args);\r
 \r
   //\r
-  // Get data size\r
+  // No matches were found \r
   //\r
-  VarDataSize = DataSizeOfVariable (Variable.CurrPtr);\r
-  ASSERT (VarDataSize != 0);\r
+  return NULL;\r
+}\r
 \r
-  if (*DataSize >= VarDataSize) {\r
-    if (Data == NULL) {\r
-      Status = EFI_INVALID_PARAMETER;\r
-      goto Done;\r
-    }\r
+/**\r
+  This function is to check if the remaining variable space is enough to set\r
+  all Variables from argument list successfully. The purpose of the check\r
+  is to keep the consistency of the Variables to be in variable storage.\r
 \r
-    CopyMem (Data, GetVariableDataPtr (Variable.CurrPtr), VarDataSize);\r
-    if (Attributes != NULL) {\r
-      *Attributes = Variable.CurrPtr->Attributes;\r
-    }\r
+  Note: Variables are assumed to be in same storage.\r
+  The set sequence of Variables will be same with the sequence of VariableEntry from argument list,\r
+  so follow the argument sequence to check the Variables.\r
 \r
-    *DataSize = VarDataSize;\r
-    UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE);\r
-    UpdateVariableCache (VariableName, VendorGuid, Variable.CurrPtr->Attributes, VarDataSize, Data);\r
\r
-    Status = EFI_SUCCESS;\r
-    goto Done;\r
-  } else {\r
-    *DataSize = VarDataSize;\r
-    Status = EFI_BUFFER_TOO_SMALL;\r
-    goto Done;\r
+  @param[in] Attributes         Variable attributes for Variable entries.\r
+  @param ...                    The variable argument list with type VARIABLE_ENTRY_CONSISTENCY *.\r
+                                A NULL terminates the list. The VariableSize of \r
+                                VARIABLE_ENTRY_CONSISTENCY is the variable data size as input.\r
+                                It will be changed to variable total size as output.\r
+\r
+  @retval TRUE                  Have enough variable space to set the Variables successfully.\r
+  @retval FALSE                 No enough variable space to set the Variables successfully.\r
+\r
+**/\r
+BOOLEAN\r
+EFIAPI\r
+CheckRemainingSpaceForConsistency (\r
+  IN UINT32                     Attributes,\r
+  ...\r
+  )\r
+{\r
+  EFI_STATUS                    Status;\r
+  VA_LIST                       Args;\r
+  VARIABLE_ENTRY_CONSISTENCY    *VariableEntry;\r
+  UINT64                        MaximumVariableStorageSize;\r
+  UINT64                        RemainingVariableStorageSize;\r
+  UINT64                        MaximumVariableSize;\r
+  UINTN                         TotalNeededSize;\r
+  UINTN                         OriginalVarSize;\r
+  VARIABLE_STORE_HEADER         *VariableStoreHeader;\r
+  VARIABLE_POINTER_TRACK        VariablePtrTrack;\r
+  VARIABLE_HEADER               *NextVariable;\r
+  UINTN                         VarNameSize;\r
+  UINTN                         VarDataSize;\r
+\r
+  //\r
+  // Non-Volatile related.\r
+  //\r
+  VariableStoreHeader = mNvVariableCache;\r
+\r
+  Status = VariableServiceQueryVariableInfoInternal (\r
+             Attributes,\r
+             &MaximumVariableStorageSize,\r
+             &RemainingVariableStorageSize,\r
+             &MaximumVariableSize\r
+             );\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  TotalNeededSize = 0;\r
+  VA_START (Args, Attributes);\r
+  VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);\r
+  while (VariableEntry != NULL) {\r
+    //\r
+    // Calculate variable total size.\r
+    //\r
+    VarNameSize  = StrSize (VariableEntry->Name);\r
+    VarNameSize += GET_PAD_SIZE (VarNameSize);\r
+    VarDataSize  = VariableEntry->VariableSize;\r
+    VarDataSize += GET_PAD_SIZE (VarDataSize);\r
+    VariableEntry->VariableSize = HEADER_ALIGN (sizeof (VARIABLE_HEADER) + VarNameSize + VarDataSize);\r
+\r
+    TotalNeededSize += VariableEntry->VariableSize;\r
+    VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);\r
   }\r
+  VA_END (Args);\r
 \r
-Done:\r
-  ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
-  return Status;\r
-}\r
+  if (RemainingVariableStorageSize >= TotalNeededSize) {\r
+    //\r
+    // Already have enough space.\r
+    //\r
+    return TRUE;\r
+  } else if (AtRuntime ()) {\r
+    //\r
+    // At runtime, no reclaim.\r
+    // The original variable space of Variables can't be reused.\r
+    //\r
+    return FALSE;\r
+  }\r
 \r
+  VA_START (Args, Attributes);\r
+  VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);\r
+  while (VariableEntry != NULL) {\r
+    //\r
+    // Check if Variable[Index] has been present and get its size.\r
+    //\r
+    OriginalVarSize = 0;\r
+    VariablePtrTrack.StartPtr = GetStartPointer (VariableStoreHeader);\r
+    VariablePtrTrack.EndPtr   = GetEndPointer   (VariableStoreHeader);\r
+    Status = FindVariableEx (\r
+               VariableEntry->Name,\r
+               VariableEntry->Guid,\r
+               FALSE,\r
+               &VariablePtrTrack\r
+               );\r
+    if (!EFI_ERROR (Status)) {\r
+      //\r
+      // Get size of Variable[Index].\r
+      //\r
+      NextVariable = GetNextVariablePtr (VariablePtrTrack.CurrPtr);\r
+      OriginalVarSize = (UINTN) NextVariable - (UINTN) VariablePtrTrack.CurrPtr;\r
+      //\r
+      // Add the original size of Variable[Index] to remaining variable storage size.\r
+      //\r
+      RemainingVariableStorageSize += OriginalVarSize;\r
+    }\r
+    if (VariableEntry->VariableSize > RemainingVariableStorageSize) {\r
+      //\r
+      // No enough space for Variable[Index].\r
+      //\r
+      VA_END (Args);\r
+      return FALSE;\r
+    }\r
+    //\r
+    // Sub the (new) size of Variable[Index] from remaining variable storage size.\r
+    //\r
+    RemainingVariableStorageSize -= VariableEntry->VariableSize;\r
+    VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);\r
+  }\r
+  VA_END (Args);\r
 \r
+  return TRUE;\r
+}\r
 \r
 /**\r
+  Hook the operations in PlatformLangCodes, LangCodes, PlatformLang and Lang.\r
 \r
-  This code Finds the Next available variable.\r
+  When setting Lang/LangCodes, simultaneously update PlatformLang/PlatformLangCodes.\r
+\r
+  According to UEFI spec, PlatformLangCodes/LangCodes are only set once in firmware initialization,\r
+  and are read-only. Therefore, in variable driver, only store the original value for other use.\r
+\r
+  @param[in] VariableName       Name of variable.\r
+\r
+  @param[in] Data               Variable data.\r
 \r
-  @param VariableNameSize           Size of the variable name\r
-  @param VariableName               Pointer to variable name\r
-  @param VendorGuid                 Variable Vendor Guid\r
+  @param[in] DataSize           Size of data. 0 means delete.\r
 \r
-  @return EFI_INVALID_PARAMETER     Invalid parameter\r
-  @return EFI_SUCCESS               Find the specified variable\r
-  @return EFI_NOT_FOUND             Not found\r
-  @return EFI_BUFFER_TO_SMALL       DataSize is too small for the result\r
+  @retval EFI_SUCCESS           The update operation is successful or ignored.\r
+  @retval EFI_WRITE_PROTECTED   Update PlatformLangCodes/LangCodes at runtime.\r
+  @retval EFI_OUT_OF_RESOURCES  No enough variable space to do the update operation.\r
+  @retval Others                Other errors happened during the update operation.\r
 \r
 **/\r
 EFI_STATUS\r
-EFIAPI\r
-RuntimeServiceGetNextVariableName (\r
-  IN OUT  UINTN             *VariableNameSize,\r
-  IN OUT  CHAR16            *VariableName,\r
-  IN OUT  EFI_GUID          *VendorGuid\r
+AutoUpdateLangVariable (\r
+  IN  CHAR16             *VariableName,\r
+  IN  VOID               *Data,\r
+  IN  UINTN              DataSize\r
   )\r
 {\r
-  VARIABLE_POINTER_TRACK  Variable;\r
-  UINTN                   VarNameSize;\r
-  EFI_STATUS              Status;\r
+  EFI_STATUS             Status;\r
+  CHAR8                  *BestPlatformLang;\r
+  CHAR8                  *BestLang;\r
+  UINTN                  Index;\r
+  UINT32                 Attributes;\r
+  VARIABLE_POINTER_TRACK Variable;\r
+  BOOLEAN                SetLanguageCodes;\r
+  VARIABLE_ENTRY_CONSISTENCY VariableEntry[2];\r
 \r
-  if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {\r
-    return EFI_INVALID_PARAMETER;\r
+  //\r
+  // Don't do updates for delete operation\r
+  //\r
+  if (DataSize == 0) {\r
+    return EFI_SUCCESS;\r
   }\r
 \r
-  AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
+  SetLanguageCodes = FALSE;\r
 \r
-  Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal);\r
-  if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {\r
-    goto Done;\r
-  }\r
+  if (StrCmp (VariableName, EFI_PLATFORM_LANG_CODES_VARIABLE_NAME) == 0) {\r
+    //\r
+    // PlatformLangCodes is a volatile variable, so it can not be updated at runtime.\r
+    //\r
+    if (AtRuntime ()) {\r
+      return EFI_WRITE_PROTECTED;\r
+    }\r
+\r
+    SetLanguageCodes = TRUE;\r
 \r
-  if (VariableName[0] != 0) {\r
     //\r
-    // If variable name is not NULL, get next variable\r
+    // According to UEFI spec, PlatformLangCodes is only set once in firmware initialization, and is read-only\r
+    // Therefore, in variable driver, only store the original value for other use.\r
     //\r
-    Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);\r
+    if (mVariableModuleGlobal->PlatformLangCodes != NULL) {\r
+      FreePool (mVariableModuleGlobal->PlatformLangCodes);\r
+    }\r
+    mVariableModuleGlobal->PlatformLangCodes = AllocateRuntimeCopyPool (DataSize, Data);\r
+    ASSERT (mVariableModuleGlobal->PlatformLangCodes != NULL);\r
+\r
+    //\r
+    // PlatformLang holds a single language from PlatformLangCodes, \r
+    // so the size of PlatformLangCodes is enough for the PlatformLang.\r
+    //\r
+    if (mVariableModuleGlobal->PlatformLang != NULL) {\r
+      FreePool (mVariableModuleGlobal->PlatformLang);\r
+    }\r
+    mVariableModuleGlobal->PlatformLang = AllocateRuntimePool (DataSize);\r
+    ASSERT (mVariableModuleGlobal->PlatformLang != NULL);\r
+\r
+  } else if (StrCmp (VariableName, EFI_LANG_CODES_VARIABLE_NAME) == 0) {\r
+    //\r
+    // LangCodes is a volatile variable, so it can not be updated at runtime.\r
+    //\r
+    if (AtRuntime ()) {\r
+      return EFI_WRITE_PROTECTED;\r
+    }\r
+\r
+    SetLanguageCodes = TRUE;\r
+\r
+    //\r
+    // According to UEFI spec, LangCodes is only set once in firmware initialization, and is read-only\r
+    // Therefore, in variable driver, only store the original value for other use.\r
+    //\r
+    if (mVariableModuleGlobal->LangCodes != NULL) {\r
+      FreePool (mVariableModuleGlobal->LangCodes);\r
+    }\r
+    mVariableModuleGlobal->LangCodes = AllocateRuntimeCopyPool (DataSize, Data);\r
+    ASSERT (mVariableModuleGlobal->LangCodes != NULL);\r
   }\r
 \r
-  while (TRUE) {\r
+  if (SetLanguageCodes \r
+      && (mVariableModuleGlobal->PlatformLangCodes != NULL)\r
+      && (mVariableModuleGlobal->LangCodes != NULL)) {\r
     //\r
-    // If both volatile and non-volatile variable store are parsed,\r
-    // return not found\r
+    // Update Lang if PlatformLang is already set\r
+    // Update PlatformLang if Lang is already set\r
     //\r
-    if (Variable.CurrPtr >= Variable.EndPtr || Variable.CurrPtr == NULL) {\r
-      Variable.Volatile = (BOOLEAN) (Variable.Volatile ^ ((BOOLEAN) 0x1));\r
-      if (!Variable.Volatile) {\r
-        Variable.StartPtr = GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase);\r
-        Variable.EndPtr   = GetEndPointer ((VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase));\r
+    Status = FindVariable (EFI_PLATFORM_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
+    if (!EFI_ERROR (Status)) {\r
+      //\r
+      // Update Lang\r
+      //\r
+      VariableName = EFI_PLATFORM_LANG_VARIABLE_NAME;\r
+      Data         = GetVariableDataPtr (Variable.CurrPtr);\r
+      DataSize     = Variable.CurrPtr->DataSize;\r
+    } else {\r
+      Status = FindVariable (EFI_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
+      if (!EFI_ERROR (Status)) {\r
+        //\r
+        // Update PlatformLang\r
+        //\r
+        VariableName = EFI_LANG_VARIABLE_NAME;\r
+        Data         = GetVariableDataPtr (Variable.CurrPtr);\r
+        DataSize     = Variable.CurrPtr->DataSize;\r
       } else {\r
-        Status = EFI_NOT_FOUND;\r
-        goto Done;\r
+        //\r
+        // Neither PlatformLang nor Lang is set, directly return\r
+        //\r
+        return EFI_SUCCESS;\r
       }\r
+    }\r
+  }\r
 \r
-      Variable.CurrPtr = Variable.StartPtr;\r
-      if (!IsValidVariableHeader (Variable.CurrPtr)) {\r
-        continue;\r
+  Status = EFI_SUCCESS;\r
+\r
+  //\r
+  // According to UEFI spec, "Lang" and "PlatformLang" is NV|BS|RT attributions.\r
+  //\r
+  Attributes = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS;\r
+\r
+  if (StrCmp (VariableName, EFI_PLATFORM_LANG_VARIABLE_NAME) == 0) {\r
+    //\r
+    // Update Lang when PlatformLangCodes/LangCodes were set.\r
+    //\r
+    if ((mVariableModuleGlobal->PlatformLangCodes != NULL) && (mVariableModuleGlobal->LangCodes != NULL)) {\r
+      //\r
+      // When setting PlatformLang, firstly get most matched language string from supported language codes.\r
+      //\r
+      BestPlatformLang = VariableGetBestLanguage (mVariableModuleGlobal->PlatformLangCodes, FALSE, Data, NULL);\r
+      if (BestPlatformLang != NULL) {\r
+        //\r
+        // Get the corresponding index in language codes.\r
+        //\r
+        Index = GetIndexFromSupportedLangCodes (mVariableModuleGlobal->PlatformLangCodes, BestPlatformLang, FALSE);\r
+\r
+        //\r
+        // Get the corresponding ISO639 language tag according to RFC4646 language tag.\r
+        //\r
+        BestLang = GetLangFromSupportedLangCodes (mVariableModuleGlobal->LangCodes, Index, TRUE);\r
+\r
+        //\r
+        // Check the variable space for both Lang and PlatformLang variable.\r
+        //\r
+        VariableEntry[0].VariableSize = ISO_639_2_ENTRY_SIZE + 1;\r
+        VariableEntry[0].Guid = &gEfiGlobalVariableGuid;\r
+        VariableEntry[0].Name = EFI_LANG_VARIABLE_NAME;\r
+        \r
+        VariableEntry[1].VariableSize = AsciiStrSize (BestPlatformLang);\r
+        VariableEntry[1].Guid = &gEfiGlobalVariableGuid;\r
+        VariableEntry[1].Name = EFI_PLATFORM_LANG_VARIABLE_NAME;\r
+        if (!CheckRemainingSpaceForConsistency (VARIABLE_ATTRIBUTE_NV_BS_RT, &VariableEntry[0], &VariableEntry[1], NULL)) {\r
+          //\r
+          // No enough variable space to set both Lang and PlatformLang successfully.\r
+          //\r
+          Status = EFI_OUT_OF_RESOURCES;\r
+        } else {\r
+          //\r
+          // Successfully convert PlatformLang to Lang, and set the BestLang value into Lang variable simultaneously.\r
+          //\r
+          FindVariable (EFI_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
+\r
+          Status = UpdateVariable (EFI_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, BestLang,\r
+                                   ISO_639_2_ENTRY_SIZE + 1, Attributes, &Variable);\r
+        }\r
+\r
+        DEBUG ((EFI_D_INFO, "Variable Driver Auto Update PlatformLang, PlatformLang:%a, Lang:%a Status: %r\n", BestPlatformLang, BestLang, Status));\r
       }\r
     }\r
+\r
+  } else if (StrCmp (VariableName, EFI_LANG_VARIABLE_NAME) == 0) {\r
     //\r
-    // Variable is found\r
+    // Update PlatformLang when PlatformLangCodes/LangCodes were set.\r
     //\r
-    if (IsValidVariableHeader (Variable.CurrPtr) && Variable.CurrPtr->State == VAR_ADDED) {\r
-      if (!(EfiAtRuntime () && !(Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS))) {\r
-        VarNameSize = NameSizeOfVariable (Variable.CurrPtr);\r
-        ASSERT (VarNameSize != 0);\r
+    if ((mVariableModuleGlobal->PlatformLangCodes != NULL) && (mVariableModuleGlobal->LangCodes != NULL)) {\r
+      //\r
+      // When setting Lang, firstly get most matched language string from supported language codes.\r
+      //\r
+      BestLang = VariableGetBestLanguage (mVariableModuleGlobal->LangCodes, TRUE, Data, NULL);\r
+      if (BestLang != NULL) {\r
+        //\r
+        // Get the corresponding index in language codes.\r
+        //\r
+        Index = GetIndexFromSupportedLangCodes (mVariableModuleGlobal->LangCodes, BestLang, TRUE);\r
 \r
-        if (VarNameSize <= *VariableNameSize) {\r
-          CopyMem (\r
-            VariableName,\r
-            GetVariableNamePtr (Variable.CurrPtr),\r
-            VarNameSize\r
-            );\r
-          CopyMem (\r
-            VendorGuid,\r
-            &Variable.CurrPtr->VendorGuid,\r
-            sizeof (EFI_GUID)\r
-            );\r
-          Status = EFI_SUCCESS;\r
+        //\r
+        // Get the corresponding RFC4646 language tag according to ISO639 language tag.\r
+        //\r
+        BestPlatformLang = GetLangFromSupportedLangCodes (mVariableModuleGlobal->PlatformLangCodes, Index, FALSE);\r
+\r
+        //\r
+        // Check the variable space for both PlatformLang and Lang variable.\r
+        //\r
+        VariableEntry[0].VariableSize = AsciiStrSize (BestPlatformLang);\r
+        VariableEntry[0].Guid = &gEfiGlobalVariableGuid;\r
+        VariableEntry[0].Name = EFI_PLATFORM_LANG_VARIABLE_NAME;\r
+\r
+        VariableEntry[1].VariableSize = ISO_639_2_ENTRY_SIZE + 1;\r
+        VariableEntry[1].Guid = &gEfiGlobalVariableGuid;\r
+        VariableEntry[1].Name = EFI_LANG_VARIABLE_NAME;\r
+        if (!CheckRemainingSpaceForConsistency (VARIABLE_ATTRIBUTE_NV_BS_RT, &VariableEntry[0], &VariableEntry[1], NULL)) {\r
+          //\r
+          // No enough variable space to set both PlatformLang and Lang successfully.\r
+          //\r
+          Status = EFI_OUT_OF_RESOURCES;\r
         } else {\r
-          Status = EFI_BUFFER_TOO_SMALL;\r
+          //\r
+          // Successfully convert Lang to PlatformLang, and set the BestPlatformLang value into PlatformLang variable simultaneously.\r
+          //\r
+          FindVariable (EFI_PLATFORM_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
+\r
+          Status = UpdateVariable (EFI_PLATFORM_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, BestPlatformLang, \r
+                                   AsciiStrSize (BestPlatformLang), Attributes, &Variable);\r
         }\r
 \r
-        *VariableNameSize = VarNameSize;\r
-        goto Done;\r
+        DEBUG ((EFI_D_INFO, "Variable Driver Auto Update Lang, Lang:%a, PlatformLang:%a Status: %r\n", BestLang, BestPlatformLang, Status));\r
       }\r
     }\r
-\r
-    Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);\r
   }\r
 \r
-Done:\r
-  ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
-  return Status;\r
+  if (SetLanguageCodes) {\r
+    //\r
+    // Continue to set PlatformLangCodes or LangCodes.\r
+    //\r
+    return EFI_SUCCESS;\r
+  } else {\r
+    return Status;\r
+  }\r
 }\r
 \r
 /**\r
+  Update the variable region with Variable information. These are the same \r
+  arguments as the EFI Variable services.\r
 \r
-  This code sets variable in storage blocks (Volatile or Non-Volatile).\r
-\r
-  @param VariableName                     Name of Variable to be found\r
-  @param VendorGuid                       Variable vendor GUID\r
-  @param Attributes                       Attribute value of the variable found\r
-  @param DataSize                         Size of Data found. If size is less than the\r
-                                          data, this value contains the required size.\r
-  @param Data                             Data pointer\r
-\r
-  @return EFI_INVALID_PARAMETER           Invalid parameter\r
-  @return EFI_SUCCESS                     Set successfully\r
-  @return EFI_OUT_OF_RESOURCES            Resource not enough to set variable\r
-  @return EFI_NOT_FOUND                   Not found\r
-  @return EFI_WRITE_PROTECTED             Variable is read-only\r
+  @param[in] VariableName       Name of variable.\r
+  @param[in] VendorGuid         Guid of variable.\r
+  @param[in] Data               Variable data.\r
+  @param[in] DataSize           Size of data. 0 means delete.\r
+  @param[in] Attributes         Attribues of the variable.\r
+  @param[in, out] CacheVariable The variable information which is used to keep track of variable usage.\r
+  \r
+  @retval EFI_SUCCESS           The update operation is success.\r
+  @retval EFI_OUT_OF_RESOURCES  Variable region is full, can not write other data into this region.\r
 \r
 **/\r
 EFI_STATUS\r
-EFIAPI\r
-RuntimeServiceSetVariable (\r
-  IN CHAR16                  *VariableName,\r
-  IN EFI_GUID                *VendorGuid,\r
-  IN UINT32                  Attributes,\r
-  IN UINTN                   DataSize,\r
-  IN VOID                    *Data\r
+UpdateVariable (\r
+  IN      CHAR16                      *VariableName,\r
+  IN      EFI_GUID                    *VendorGuid,\r
+  IN      VOID                        *Data,\r
+  IN      UINTN                       DataSize,\r
+  IN      UINT32                      Attributes      OPTIONAL,\r
+  IN OUT  VARIABLE_POINTER_TRACK      *CacheVariable\r
   )\r
 {\r
-  VARIABLE_POINTER_TRACK  Variable;\r
-  EFI_STATUS              Status;\r
-  VARIABLE_HEADER         *NextVariable;\r
-  UINTN                   VarNameSize;\r
-  UINTN                   VarNameOffset;\r
-  UINTN                   VarDataOffset;\r
-  UINTN                   VarSize;\r
-  UINT8                   State;\r
-  BOOLEAN                 Reclaimed;\r
-  UINTN                   *VolatileOffset;\r
-  UINTN                   *NonVolatileOffset;\r
-  UINT32                  Instance;\r
-  BOOLEAN                 Volatile;\r
-  EFI_PHYSICAL_ADDRESS    Point;\r
-\r
-  //\r
-  // Check input parameters\r
-  //\r
-  if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {\r
-    return EFI_INVALID_PARAMETER;\r
-  }  \r
-  //\r
-  //  Make sure if runtime bit is set, boot service bit is set also\r
-  //\r
-  if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {\r
-    return EFI_INVALID_PARAMETER;\r
+  EFI_STATUS                          Status;\r
+  VARIABLE_HEADER                     *NextVariable;\r
+  UINTN                               ScratchSize;\r
+  UINTN                               NonVolatileVarableStoreSize;\r
+  UINTN                               VarNameOffset;\r
+  UINTN                               VarDataOffset;\r
+  UINTN                               VarNameSize;\r
+  UINTN                               VarSize;\r
+  BOOLEAN                             Volatile;\r
+  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL  *Fvb;\r
+  UINT8                               State;\r
+  VARIABLE_POINTER_TRACK              *Variable;\r
+  VARIABLE_POINTER_TRACK              NvVariable;\r
+  VARIABLE_STORE_HEADER               *VariableStoreHeader;\r
+  UINTN                               CacheOffset;\r
+\r
+  if ((mVariableModuleGlobal->FvbInstance == NULL) && ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0)) {\r
+    //\r
+    // The FVB protocol is not ready. Trying to update NV variable prior to the installation\r
+    // of EFI_VARIABLE_WRITE_ARCH_PROTOCOL.\r
+    //\r
+    return EFI_NOT_AVAILABLE_YET;     \r
   }\r
 \r
-  //\r
-  //  The size of the VariableName, including the Unicode Null in bytes plus\r
-  //  the DataSize is limited to maximum size of FixedPcdGet32(PcdMaxHardwareErrorVariableSize)\r
-  //  bytes for HwErrRec, and FixedPcdGet32(PcdMaxVariableSize) bytes for the others.\r
-  //\r
-  if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
-    if ((DataSize > FixedPcdGet32(PcdMaxHardwareErrorVariableSize)) ||                                                       \r
-        (sizeof (VARIABLE_HEADER) + StrSize (VariableName) + DataSize > FixedPcdGet32(PcdMaxHardwareErrorVariableSize))) {\r
-      return EFI_INVALID_PARAMETER;\r
-    }    \r
+  if ((CacheVariable->CurrPtr == NULL) || CacheVariable->Volatile) {\r
+    Variable = CacheVariable;\r
   } else {\r
-  //\r
-  //  The size of the VariableName, including the Unicode Null in bytes plus\r
-  //  the DataSize is limited to maximum size of FixedPcdGet32(PcdMaxVariableSize) bytes.\r
-  //\r
-    if ((DataSize > FixedPcdGet32(PcdMaxVariableSize)) ||\r
-        (sizeof (VARIABLE_HEADER) + StrSize (VariableName) + DataSize > FixedPcdGet32(PcdMaxVariableSize))) {\r
-      return EFI_INVALID_PARAMETER;\r
-    }  \r
-  }  \r
-\r
-  AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
-\r
-  Reclaimed         = FALSE;\r
-  Instance          = mVariableModuleGlobal->FvbInstance;\r
-  VolatileOffset    = &mVariableModuleGlobal->VolatileLastVariableOffset;\r
-\r
-  //\r
-  // Consider reentrant in MCA/INIT/NMI. It needs be reupdated;\r
-  //\r
-  if (1 < InterlockedIncrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState)) {\r
-    Point = mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;;\r
     //\r
-    // Parse non-volatile variable data and get last variable offset\r
+    // Update/Delete existing NV variable.\r
+    // CacheVariable points to the variable in the memory copy of Flash area\r
+    // Now let Variable points to the same variable in Flash area.\r
     //\r
-    NextVariable  = GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point);\r
-    while (IsValidVariableHeader (NextVariable)) {\r
-      NextVariable = GetNextVariablePtr (NextVariable);\r
+    VariableStoreHeader  = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase);\r
+    Variable = &NvVariable;    \r
+    Variable->StartPtr = GetStartPointer (VariableStoreHeader);\r
+    Variable->EndPtr   = GetEndPointer (VariableStoreHeader);\r
+    Variable->CurrPtr  = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->CurrPtr - (UINTN)CacheVariable->StartPtr));\r
+    if (CacheVariable->InDeletedTransitionPtr != NULL) {\r
+      Variable->InDeletedTransitionPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->InDeletedTransitionPtr - (UINTN)CacheVariable->StartPtr));\r
+    } else {\r
+      Variable->InDeletedTransitionPtr = NULL;\r
     }\r
-    mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) Point;\r
-  }\r
+    Variable->Volatile = FALSE;\r
+  } \r
 \r
-  NonVolatileOffset = &mVariableModuleGlobal->NonVolatileLastVariableOffset;\r
-  \r
+  Fvb       = mVariableModuleGlobal->FvbInstance;\r
 \r
-  //\r
-  // Check whether the input variable is already existed\r
-  //\r
-  \r
-  Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal);\r
-  if (Status == EFI_SUCCESS && Variable.CurrPtr != NULL) {\r
+  if (Variable->CurrPtr != NULL) {\r
     //\r
-    // Update/Delete existing variable\r
+    // Update/Delete existing variable.\r
     //\r
-    Volatile = Variable.Volatile;\r
-    \r
-    if (EfiAtRuntime ()) {        \r
+    if (AtRuntime ()) {        \r
       //\r
-      // If EfiAtRuntime and the variable is Volatile and Runtime Access,  \r
+      // If AtRuntime and the variable is Volatile and Runtime Access,  \r
       // the volatile is ReadOnly, and SetVariable should be aborted and \r
       // return EFI_WRITE_PROTECTED.\r
       //\r
-      if (Variable.Volatile) {\r
+      if (Variable->Volatile) {\r
         Status = EFI_WRITE_PROTECTED;\r
         goto Done;\r
       }\r
       //\r
-      // Only variable have NV attribute can be updated/deleted in Runtime\r
+      // Only variable that have NV|RT attributes can be updated/deleted in Runtime.\r
       //\r
-      if (!(Variable.CurrPtr->Attributes & EFI_VARIABLE_NON_VOLATILE)) {\r
+      if (((Variable->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) || ((Variable->CurrPtr->Attributes & EFI_VARIABLE_NON_VOLATILE) == 0)) {\r
         Status = EFI_INVALID_PARAMETER;\r
         goto Done;      \r
       }\r
     }\r
+\r
     //\r
     // Setting a data variable with no access, or zero DataSize attributes\r
-    // specified causes it to be deleted.\r
+    // causes it to be deleted.\r
     //\r
     if (DataSize == 0 || (Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0) {    \r
-      State = Variable.CurrPtr->State;\r
+      if (Variable->InDeletedTransitionPtr != NULL) {\r
+        //\r
+        // Both ADDED and IN_DELETED_TRANSITION variable are present,\r
+        // set IN_DELETED_TRANSITION one to DELETED state first.\r
+        //\r
+        State = Variable->InDeletedTransitionPtr->State;\r
+        State &= VAR_DELETED;\r
+        Status = UpdateVariableStore (\r
+                   &mVariableModuleGlobal->VariableGlobal,\r
+                   Variable->Volatile,\r
+                   FALSE,\r
+                   Fvb,\r
+                   (UINTN) &Variable->InDeletedTransitionPtr->State,\r
+                   sizeof (UINT8),\r
+                   &State\r
+                   );\r
+        if (!EFI_ERROR (Status)) {\r
+          if (!Variable->Volatile) {\r
+            ASSERT (CacheVariable->InDeletedTransitionPtr != NULL);\r
+            CacheVariable->InDeletedTransitionPtr->State = State;\r
+          }\r
+        } else {\r
+          goto Done;\r
+        }\r
+      }\r
+\r
+      State = Variable->CurrPtr->State;\r
       State &= VAR_DELETED;\r
 \r
       Status = UpdateVariableStore (\r
                  &mVariableModuleGlobal->VariableGlobal,\r
-                 Variable.Volatile,\r
+                 Variable->Volatile,\r
                  FALSE,\r
-                 Instance,\r
-                 (UINTN) &Variable.CurrPtr->State,\r
+                 Fvb,\r
+                 (UINTN) &Variable->CurrPtr->State,\r
                  sizeof (UINT8),\r
                  &State\r
                  ); \r
       if (!EFI_ERROR (Status)) {\r
-        UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, FALSE, TRUE, FALSE);\r
-        UpdateVariableCache (VariableName, VendorGuid, Attributes, DataSize, Data);\r
+        UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, FALSE, TRUE, FALSE);\r
+        if (!Variable->Volatile) {\r
+          CacheVariable->CurrPtr->State = State;\r
+          FlushHobVariableToFlash (VariableName, VendorGuid);\r
+        }\r
       }\r
       goto Done;     \r
     }\r
     //\r
-    // If the variable is marked valid and the same data has been passed in\r
+    // If the variable is marked valid, and the same data has been passed in,\r
     // then return to the caller immediately.\r
     //\r
-    if (DataSizeOfVariable (Variable.CurrPtr) == DataSize &&\r
-        (CompareMem (Data, GetVariableDataPtr (Variable.CurrPtr), DataSize) == 0)) {\r
+    if (DataSizeOfVariable (Variable->CurrPtr) == DataSize &&\r
+        (CompareMem (Data, GetVariableDataPtr (Variable->CurrPtr), DataSize) == 0)) {\r
       \r
-      UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE);\r
+      UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE);\r
       Status = EFI_SUCCESS;\r
       goto Done;\r
-    } else if ((Variable.CurrPtr->State == VAR_ADDED) ||\r
-               (Variable.CurrPtr->State == (VAR_ADDED & VAR_IN_DELETED_TRANSITION))) {\r
+    } else if ((Variable->CurrPtr->State == VAR_ADDED) ||\r
+               (Variable->CurrPtr->State == (VAR_ADDED & VAR_IN_DELETED_TRANSITION))) {\r
 \r
       //\r
-      // Mark the old variable as in delete transition\r
+      // Mark the old variable as in delete transition.\r
       //\r
-      State = Variable.CurrPtr->State;\r
+      State = Variable->CurrPtr->State;\r
       State &= VAR_IN_DELETED_TRANSITION;\r
 \r
       Status = UpdateVariableStore (\r
                  &mVariableModuleGlobal->VariableGlobal,\r
-                 Variable.Volatile,\r
+                 Variable->Volatile,\r
                  FALSE,\r
-                 Instance,\r
-                 (UINTN) &Variable.CurrPtr->State,\r
+                 Fvb,\r
+                 (UINTN) &Variable->CurrPtr->State,\r
                  sizeof (UINT8),\r
                  &State\r
                  );      \r
       if (EFI_ERROR (Status)) {\r
         goto Done;  \r
       } \r
+      if (!Variable->Volatile) {\r
+        CacheVariable->CurrPtr->State = State;\r
+      }\r
     }    \r
-  } else if (Status == EFI_NOT_FOUND) {\r
+  } else {\r
     //\r
-    // Create a new variable\r
+    // Not found existing variable. Create a new variable.\r
     //  \r
     \r
     //\r
     // Make sure we are trying to create a new variable.\r
-    // Setting a data variable with no access, or zero DataSize attributes means to delete it.    \r
+    // Setting a data variable with zero DataSize or no access attributes means to delete it.    \r
     //\r
     if (DataSize == 0 || (Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0) {\r
       Status = EFI_NOT_FOUND;\r
@@ -1369,40 +1828,36 @@ RuntimeServiceSetVariable (
     }\r
         \r
     //\r
-    // Only variable have NV|RT attribute can be created in Runtime\r
+    // Only variable have NV|RT attribute can be created in Runtime.\r
     //\r
-    if (EfiAtRuntime () &&\r
+    if (AtRuntime () &&\r
         (((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) || ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0))) {\r
       Status = EFI_INVALID_PARAMETER;\r
       goto Done;\r
     }         \r
-  } else {\r
-    //\r
-    // Status should be EFI_INVALID_PARAMETER here according to return status of FindVariable().\r
-    //\r
-    ASSERT (Status == EFI_INVALID_PARAMETER);\r
-    goto Done;\r
   }\r
 \r
   //\r
   // Function part - create a new variable and copy the data.\r
   // Both update a variable and create a variable will come here.\r
+\r
   //\r
   // Tricky part: Use scratch data area at the end of volatile variable store\r
   // as a temporary storage.\r
   //\r
   NextVariable = GetEndPointer ((VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase));\r
+  ScratchSize = MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize));\r
 \r
-  SetMem (NextVariable, FixedPcdGet32(PcdMaxVariableSize), 0xff);\r
+  SetMem (NextVariable, ScratchSize, 0xff);\r
 \r
   NextVariable->StartId     = VARIABLE_DATA;\r
   NextVariable->Attributes  = Attributes;\r
   //\r
   // NextVariable->State = VAR_ADDED;\r
   //\r
-  NextVariable->Reserved  = 0;\r
-  VarNameOffset           = sizeof (VARIABLE_HEADER);\r
-  VarNameSize             = StrSize (VariableName);\r
+  NextVariable->Reserved        = 0;\r
+  VarNameOffset                 = sizeof (VARIABLE_HEADER);\r
+  VarNameSize                   = StrSize (VariableName);\r
   CopyMem (\r
     (UINT8 *) ((UINTN) NextVariable + VarNameOffset),\r
     VariableName,\r
@@ -1418,7 +1873,7 @@ RuntimeServiceSetVariable (
   //\r
   // There will be pad bytes after Data, the NextVariable->NameSize and\r
   // NextVariable->DataSize should not include pad size so that variable\r
-  // service can get actual size in GetVariable\r
+  // service can get actual size in GetVariable.\r
   //\r
   NextVariable->NameSize  = (UINT32)VarNameSize;\r
   NextVariable->DataSize  = (UINT32)DataSize;\r
@@ -1430,38 +1885,38 @@ RuntimeServiceSetVariable (
   VarSize = VarDataOffset + DataSize + GET_PAD_SIZE (DataSize);\r
   if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {\r
     //\r
-    // Create a nonvolatile variable\r
+    // Create a nonvolatile variable.\r
     //\r
     Volatile = FALSE;\r
-    \r
-    if ((UINT32) (VarSize +*NonVolatileOffset) >\r
-          ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase)))->Size\r
-          ) {\r
-      if (EfiAtRuntime ()) {\r
+    NonVolatileVarableStoreSize = ((VARIABLE_STORE_HEADER *)(UINTN)(mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase))->Size;\r
+    if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) \r
+      && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize)))\r
+      || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0) \r
+      && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > NonVolatileVarableStoreSize - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize)))) {\r
+      if (AtRuntime ()) {\r
         Status = EFI_OUT_OF_RESOURCES;\r
         goto Done;\r
       }\r
       //\r
-      // Perform garbage collection & reclaim operation\r
-      //\r
-      Status = Reclaim (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase, NonVolatileOffset, FALSE, Variable.CurrPtr);\r
-      if (EFI_ERROR (Status)) {\r
-        goto Done;\r
-      }\r
-      //\r
-      // If still no enough space, return out of resources\r
+      // Perform garbage collection & reclaim operation, and integrate the new variable at the same time.\r
       //\r
-      if ((UINT32) (VarSize +*NonVolatileOffset) >\r
-            ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase)))->Size\r
-            ) {\r
-        Status = EFI_OUT_OF_RESOURCES;\r
-        goto Done;\r
+      Status = Reclaim (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase, \r
+                        &mVariableModuleGlobal->NonVolatileLastVariableOffset, FALSE, Variable, NextVariable, HEADER_ALIGN (VarSize));\r
+      if (!EFI_ERROR (Status)) {\r
+        //\r
+        // The new variable has been integrated successfully during reclaiming.\r
+        //\r
+        if (Variable->CurrPtr != NULL) {\r
+          CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));\r
+          CacheVariable->InDeletedTransitionPtr = NULL;\r
+        }\r
+        UpdateVariableInfo (VariableName, VendorGuid, FALSE, FALSE, TRUE, FALSE, FALSE);\r
+        FlushHobVariableToFlash (VariableName, VendorGuid);\r
       }\r
-      \r
-      Reclaimed = TRUE;\r
+      goto Done;\r
     }\r
     //\r
-    // Three steps\r
+    // Four steps\r
     // 1. Write variable header\r
     // 2. Set variable state to header valid  \r
     // 3. Write variable data\r
@@ -1470,12 +1925,13 @@ RuntimeServiceSetVariable (
     //\r
     // Step 1:\r
     //\r
+    CacheOffset = mVariableModuleGlobal->NonVolatileLastVariableOffset;\r
     Status = UpdateVariableStore (\r
                &mVariableModuleGlobal->VariableGlobal,\r
                FALSE,\r
                TRUE,\r
-               Instance,\r
-               *NonVolatileOffset,\r
+               Fvb,\r
+               mVariableModuleGlobal->NonVolatileLastVariableOffset,\r
                sizeof (VARIABLE_HEADER),\r
                (UINT8 *) NextVariable\r
                );\r
@@ -1492,10 +1948,10 @@ RuntimeServiceSetVariable (
                &mVariableModuleGlobal->VariableGlobal,\r
                FALSE,\r
                TRUE,\r
-               Instance,\r
-               *NonVolatileOffset,\r
-               sizeof (VARIABLE_HEADER),\r
-               (UINT8 *) NextVariable\r
+               Fvb,\r
+               mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),\r
+               sizeof (UINT8),\r
+               &NextVariable->State\r
                );\r
 \r
     if (EFI_ERROR (Status)) {\r
@@ -1508,8 +1964,8 @@ RuntimeServiceSetVariable (
                &mVariableModuleGlobal->VariableGlobal,\r
                FALSE,\r
                TRUE,\r
-               Instance,\r
-               *NonVolatileOffset + sizeof (VARIABLE_HEADER),\r
+               Fvb,\r
+               mVariableModuleGlobal->NonVolatileLastVariableOffset + sizeof (VARIABLE_HEADER),\r
                (UINT32) VarSize - sizeof (VARIABLE_HEADER),\r
                (UINT8 *) NextVariable + sizeof (VARIABLE_HEADER)\r
                );\r
@@ -1525,44 +1981,51 @@ RuntimeServiceSetVariable (
                &mVariableModuleGlobal->VariableGlobal,\r
                FALSE,\r
                TRUE,\r
-               Instance,\r
-               *NonVolatileOffset,\r
-               sizeof (VARIABLE_HEADER),\r
-               (UINT8 *) NextVariable\r
+               Fvb,\r
+               mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),\r
+               sizeof (UINT8),\r
+               &NextVariable->State\r
                );\r
 \r
     if (EFI_ERROR (Status)) {\r
       goto Done;\r
     }\r
 \r
-    *NonVolatileOffset = HEADER_ALIGN (*NonVolatileOffset + VarSize);\r
+    mVariableModuleGlobal->NonVolatileLastVariableOffset += HEADER_ALIGN (VarSize);\r
 \r
+    if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) {\r
+      mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VarSize);\r
+    } else {\r
+      mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VarSize);\r
+    }\r
+    //\r
+    // update the memory copy of Flash region.\r
+    //\r
+    CopyMem ((UINT8 *)mNvVariableCache + CacheOffset, (UINT8 *)NextVariable, VarSize);\r
   } else {\r
     //\r
-    // Create a volatile variable\r
+    // Create a volatile variable.\r
     //      \r
     Volatile = TRUE;\r
 \r
-    if ((UINT32) (VarSize +*VolatileOffset) >\r
+    if ((UINT32) (VarSize + mVariableModuleGlobal->VolatileLastVariableOffset) >\r
         ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase)))->Size) {\r
       //\r
-      // Perform garbage collection & reclaim operation\r
-      //\r
-      Status = Reclaim (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase, VolatileOffset, TRUE, Variable.CurrPtr);\r
-      if (EFI_ERROR (Status)) {\r
-        goto Done;\r
-      }\r
-      //\r
-      // If still no enough space, return out of resources\r
+      // Perform garbage collection & reclaim operation, and integrate the new variable at the same time.\r
       //\r
-      if ((UINT32) (VarSize +*VolatileOffset) >\r
-            ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase)))->Size\r
-            ) {\r
-        Status = EFI_OUT_OF_RESOURCES;\r
-        goto Done;\r
+      Status = Reclaim (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase, \r
+                          &mVariableModuleGlobal->VolatileLastVariableOffset, TRUE, Variable, NextVariable, HEADER_ALIGN (VarSize));\r
+      if (!EFI_ERROR (Status)) {\r
+        //\r
+        // The new variable has been integrated successfully during reclaiming.\r
+        //\r
+        if (Variable->CurrPtr != NULL) {\r
+          CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));\r
+          CacheVariable->InDeletedTransitionPtr = NULL;\r
+        }\r
+        UpdateVariableInfo (VariableName, VendorGuid, TRUE, FALSE, TRUE, FALSE, FALSE);\r
       }\r
-      \r
-      Reclaimed = TRUE;\r
+      goto Done;\r
     }\r
 \r
     NextVariable->State = VAR_ADDED;\r
@@ -1570,8 +2033,8 @@ RuntimeServiceSetVariable (
                &mVariableModuleGlobal->VariableGlobal,\r
                TRUE,\r
                TRUE,\r
-               Instance,\r
-               *VolatileOffset,\r
+               Fvb,\r
+               mVariableModuleGlobal->VolatileLastVariableOffset,\r
                (UINT32) VarSize,\r
                (UINT8 *) NextVariable\r
                );\r
@@ -1580,498 +2043,1360 @@ RuntimeServiceSetVariable (
       goto Done;\r
     }\r
 \r
-    *VolatileOffset = HEADER_ALIGN (*VolatileOffset + VarSize);\r
+    mVariableModuleGlobal->VolatileLastVariableOffset += HEADER_ALIGN (VarSize);\r
   }\r
+\r
   //\r
-  // Mark the old variable as deleted\r
+  // Mark the old variable as deleted.\r
   //\r
-  if (!Reclaimed && !EFI_ERROR (Status) && Variable.CurrPtr != NULL) {\r
-    State = Variable.CurrPtr->State;\r
+  if (!EFI_ERROR (Status) && Variable->CurrPtr != NULL) {\r
+    if (Variable->InDeletedTransitionPtr != NULL) {\r
+      //\r
+      // Both ADDED and IN_DELETED_TRANSITION old variable are present,\r
+      // set IN_DELETED_TRANSITION one to DELETED state first.\r
+      //\r
+      State = Variable->InDeletedTransitionPtr->State;\r
+      State &= VAR_DELETED;\r
+      Status = UpdateVariableStore (\r
+                 &mVariableModuleGlobal->VariableGlobal,\r
+                 Variable->Volatile,\r
+                 FALSE,\r
+                 Fvb,\r
+                 (UINTN) &Variable->InDeletedTransitionPtr->State,\r
+                 sizeof (UINT8),\r
+                 &State\r
+                 );\r
+      if (!EFI_ERROR (Status)) {\r
+        if (!Variable->Volatile) {\r
+          ASSERT (CacheVariable->InDeletedTransitionPtr != NULL);\r
+          CacheVariable->InDeletedTransitionPtr->State = State;\r
+        }\r
+      } else {\r
+        goto Done;\r
+      }\r
+    }\r
+\r
+    State = Variable->CurrPtr->State;\r
     State &= VAR_DELETED;\r
 \r
     Status = UpdateVariableStore (\r
-               &mVariableModuleGlobal->VariableGlobal,\r
-               Variable.Volatile,\r
-               FALSE,\r
-               Instance,\r
-               (UINTN) &Variable.CurrPtr->State,\r
-               sizeof (UINT8),\r
-               &State\r
-               );\r
-    \r
-    if (!EFI_ERROR (Status)) {\r
-      UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE);\r
-      UpdateVariableCache (VariableName, VendorGuid, Attributes, DataSize, Data);\r
+             &mVariableModuleGlobal->VariableGlobal,\r
+             Variable->Volatile,\r
+             FALSE,\r
+             Fvb,\r
+             (UINTN) &Variable->CurrPtr->State,\r
+             sizeof (UINT8),\r
+             &State\r
+             );\r
+    if (!EFI_ERROR (Status) && !Variable->Volatile) {         \r
+      CacheVariable->CurrPtr->State = State;\r
     }\r
-    goto Done;      \r
   }\r
 \r
-  Status = EFI_SUCCESS;\r
-  UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE);\r
-  UpdateVariableCache (VariableName, VendorGuid, Attributes, DataSize, Data);\r
+  if (!EFI_ERROR (Status)) {\r
+    UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE);\r
+    if (!Volatile) {\r
+      FlushHobVariableToFlash (VariableName, VendorGuid);\r
+    }\r
+  }\r
 \r
 Done:\r
-  InterlockedDecrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState);\r
+  return Status;\r
+}\r
+\r
+/**\r
+  Check if a Unicode character is a hexadecimal character.\r
+\r
+  This function checks if a Unicode character is a \r
+  hexadecimal character.  The valid hexadecimal character is \r
+  L'0' to L'9', L'a' to L'f', or L'A' to L'F'.\r
+\r
+\r
+  @param Char           The character to check against.\r
+\r
+  @retval TRUE          If the Char is a hexadecmial character.\r
+  @retval FALSE         If the Char is not a hexadecmial character.\r
+\r
+**/\r
+BOOLEAN\r
+EFIAPI\r
+IsHexaDecimalDigitCharacter (\r
+  IN CHAR16             Char\r
+  )\r
+{\r
+  return (BOOLEAN) ((Char >= L'0' && Char <= L'9') || (Char >= L'A' && Char <= L'F') || (Char >= L'a' && Char <= L'f'));\r
+}\r
+\r
+/**\r
+\r
+  This code checks if variable is hardware error record variable or not.\r
+\r
+  According to UEFI spec, hardware error record variable should use the EFI_HARDWARE_ERROR_VARIABLE VendorGuid\r
+  and have the L"HwErrRec####" name convention, #### is a printed hex value and no 0x or h is included in the hex value.\r
+\r
+  @param VariableName   Pointer to variable name.\r
+  @param VendorGuid     Variable Vendor Guid.\r
+\r
+  @retval TRUE          Variable is hardware error record variable.\r
+  @retval FALSE         Variable is not hardware error record variable.\r
+\r
+**/\r
+BOOLEAN\r
+EFIAPI\r
+IsHwErrRecVariable (\r
+  IN CHAR16             *VariableName,\r
+  IN EFI_GUID           *VendorGuid\r
+  )\r
+{\r
+  if (!CompareGuid (VendorGuid, &gEfiHardwareErrorVariableGuid) ||\r
+      (StrLen (VariableName) != StrLen (L"HwErrRec####")) ||\r
+      (StrnCmp(VariableName, L"HwErrRec", StrLen (L"HwErrRec")) != 0) ||\r
+      !IsHexaDecimalDigitCharacter (VariableName[0x8]) ||\r
+      !IsHexaDecimalDigitCharacter (VariableName[0x9]) ||\r
+      !IsHexaDecimalDigitCharacter (VariableName[0xA]) ||\r
+      !IsHexaDecimalDigitCharacter (VariableName[0xB])) {\r
+    return FALSE;\r
+  }\r
+\r
+  return TRUE;\r
+}\r
+\r
+/**\r
+  This code checks if variable guid is global variable guid first.\r
+  If yes, further check if variable name is in mGlobalVariableList or mGlobalVariableList2 and attributes matched.\r
+\r
+  @param[in] VariableName       Pointer to variable name.\r
+  @param[in] VendorGuid         Variable Vendor Guid.\r
+  @param[in] Attributes         Attributes of the variable.\r
+\r
+  @retval EFI_SUCCESS           Variable is not global variable, or Variable is global variable, variable name is in the lists and attributes matched.\r
+  @retval EFI_INVALID_PARAMETER Variable is global variable, but variable name is not in the lists or attributes unmatched.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+CheckEfiGlobalVariable (\r
+  IN CHAR16             *VariableName,\r
+  IN EFI_GUID           *VendorGuid,\r
+  IN UINT32             Attributes\r
+  )\r
+{\r
+  UINTN     Index;\r
+  UINTN     NameLength;\r
+\r
+  if (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid)){\r
+    //\r
+    // Try list 1, exactly match.\r
+    //\r
+    for (Index = 0; Index < sizeof (mGlobalVariableList)/sizeof (mGlobalVariableList[0]); Index++) {\r
+      if ((StrCmp (mGlobalVariableList[Index].Name, VariableName) == 0) &&\r
+          (Attributes == 0 || Attributes == mGlobalVariableList[Index].Attributes)) {\r
+        return EFI_SUCCESS;\r
+      }\r
+    }\r
+\r
+    //\r
+    // Try list 2.\r
+    //\r
+    NameLength = StrLen (VariableName) - 4;\r
+    for (Index = 0; Index < sizeof (mGlobalVariableList2)/sizeof (mGlobalVariableList2[0]); Index++) {\r
+      if ((StrLen (VariableName) == StrLen (mGlobalVariableList2[Index].Name)) &&\r
+          (StrnCmp (mGlobalVariableList2[Index].Name, VariableName, NameLength) == 0) &&\r
+          IsHexaDecimalDigitCharacter (VariableName[NameLength]) &&\r
+          IsHexaDecimalDigitCharacter (VariableName[NameLength + 1]) &&\r
+          IsHexaDecimalDigitCharacter (VariableName[NameLength + 2]) &&\r
+          IsHexaDecimalDigitCharacter (VariableName[NameLength + 3]) &&\r
+          (Attributes == 0 || Attributes == mGlobalVariableList2[Index].Attributes)) {\r
+        return EFI_SUCCESS;\r
+      }\r
+    }\r
+\r
+    DEBUG ((EFI_D_INFO, "[Variable]: set global variable with invalid variable name or attributes - %g:%s:%x\n", VendorGuid, VariableName, Attributes));\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+/**\r
+  Mark a variable that will become read-only after leaving the DXE phase of execution.\r
+\r
+  @param[in] This          The VARIABLE_LOCK_PROTOCOL instance.\r
+  @param[in] VariableName  A pointer to the variable name that will be made read-only subsequently.\r
+  @param[in] VendorGuid    A pointer to the vendor GUID that will be made read-only subsequently.\r
+\r
+  @retval EFI_SUCCESS           The variable specified by the VariableName and the VendorGuid was marked\r
+                                as pending to be read-only.\r
+  @retval EFI_INVALID_PARAMETER VariableName or VendorGuid is NULL.\r
+                                Or VariableName is an empty string.\r
+  @retval EFI_ACCESS_DENIED     EFI_END_OF_DXE_EVENT_GROUP_GUID or EFI_EVENT_GROUP_READY_TO_BOOT has\r
+                                already been signaled.\r
+  @retval EFI_OUT_OF_RESOURCES  There is not enough resource to hold the lock request.\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+VariableLockRequestToLock (\r
+  IN CONST EDKII_VARIABLE_LOCK_PROTOCOL *This,\r
+  IN       CHAR16                       *VariableName,\r
+  IN       EFI_GUID                     *VendorGuid\r
+  )\r
+{\r
+  VARIABLE_ENTRY                  *Entry;\r
+\r
+  if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if (mEndOfDxe) {\r
+    return EFI_ACCESS_DENIED;\r
+  }\r
+\r
+  Entry = AllocateRuntimePool (sizeof (*Entry) + StrSize (VariableName));\r
+  if (Entry == NULL) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  DEBUG ((EFI_D_INFO, "[Variable] Lock: %g:%s\n", VendorGuid, VariableName));\r
+\r
+  AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
+\r
+  Entry->Name = (CHAR16 *) (Entry + 1);\r
+  StrCpy   (Entry->Name, VariableName);\r
+  CopyGuid (&Entry->Guid, VendorGuid);\r
+  InsertTailList (&mLockedVariableList, &Entry->Link);\r
+\r
   ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
 \r
+  return EFI_SUCCESS;\r
+}\r
+\r
+/**\r
+\r
+  This code finds variable in storage blocks (Volatile or Non-Volatile).\r
+\r
+  @param VariableName               Name of Variable to be found.\r
+  @param VendorGuid                 Variable vendor GUID.\r
+  @param Attributes                 Attribute value of the variable found.\r
+  @param DataSize                   Size of Data found. If size is less than the\r
+                                    data, this value contains the required size.\r
+  @param Data                       Data pointer.\r
+                      \r
+  @return EFI_INVALID_PARAMETER     Invalid parameter.\r
+  @return EFI_SUCCESS               Find the specified variable.\r
+  @return EFI_NOT_FOUND             Not found.\r
+  @return EFI_BUFFER_TO_SMALL       DataSize is too small for the result.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+VariableServiceGetVariable (\r
+  IN      CHAR16            *VariableName,\r
+  IN      EFI_GUID          *VendorGuid,\r
+  OUT     UINT32            *Attributes OPTIONAL,\r
+  IN OUT  UINTN             *DataSize,\r
+  OUT     VOID              *Data\r
+  )\r
+{\r
+  EFI_STATUS              Status;\r
+  VARIABLE_POINTER_TRACK  Variable;\r
+  UINTN                   VarDataSize;\r
+\r
+  if (VariableName == NULL || VendorGuid == NULL || DataSize == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
+  \r
+  Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
+  if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Get data size\r
+  //\r
+  VarDataSize = DataSizeOfVariable (Variable.CurrPtr);\r
+  ASSERT (VarDataSize != 0);\r
+\r
+  if (*DataSize >= VarDataSize) {\r
+    if (Data == NULL) {\r
+      Status = EFI_INVALID_PARAMETER;\r
+      goto Done;\r
+    }\r
+\r
+    CopyMem (Data, GetVariableDataPtr (Variable.CurrPtr), VarDataSize);\r
+    if (Attributes != NULL) {\r
+      *Attributes = Variable.CurrPtr->Attributes;\r
+    }\r
+\r
+    *DataSize = VarDataSize;\r
+    UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE);\r
\r
+    Status = EFI_SUCCESS;\r
+    goto Done;\r
+  } else {\r
+    *DataSize = VarDataSize;\r
+    Status = EFI_BUFFER_TOO_SMALL;\r
+    goto Done;\r
+  }\r
+\r
+Done:\r
+  ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
   return Status;\r
 }\r
 \r
+\r
+\r
 /**\r
 \r
-  This code returns information about the EFI variables.\r
+  This code Finds the Next available variable.\r
 \r
-  @param Attributes                     Attributes bitmask to specify the type of variables\r
-                                        on which to return information.\r
-  @param MaximumVariableStorageSize     Pointer to the maximum size of the storage space available\r
-                                        for the EFI variables associated with the attributes specified.\r
-  @param RemainingVariableStorageSize   Pointer to the remaining size of the storage space available\r
-                                        for EFI variables associated with the attributes specified.\r
-  @param MaximumVariableSize            Pointer to the maximum size of an individual EFI variables\r
-                                        associated with the attributes specified.\r
+  @param VariableNameSize           Size of the variable name.\r
+  @param VariableName               Pointer to variable name.\r
+  @param VendorGuid                 Variable Vendor Guid.\r
 \r
-  @return EFI_INVALID_PARAMETER         An invalid combination of attribute bits was supplied.\r
-  @return EFI_SUCCESS                   Query successfully.\r
-  @return EFI_UNSUPPORTED               The attribute is not supported on this platform.\r
+  @return EFI_INVALID_PARAMETER     Invalid parameter.\r
+  @return EFI_SUCCESS               Find the specified variable.\r
+  @return EFI_NOT_FOUND             Not found.\r
+  @return EFI_BUFFER_TO_SMALL       DataSize is too small for the result.\r
 \r
 **/\r
 EFI_STATUS\r
 EFIAPI\r
-RuntimeServiceQueryVariableInfo (\r
-  IN  UINT32                 Attributes,\r
-  OUT UINT64                 *MaximumVariableStorageSize,\r
-  OUT UINT64                 *RemainingVariableStorageSize,\r
-  OUT UINT64                 *MaximumVariableSize\r
+VariableServiceGetNextVariableName (\r
+  IN OUT  UINTN             *VariableNameSize,\r
+  IN OUT  CHAR16            *VariableName,\r
+  IN OUT  EFI_GUID          *VendorGuid\r
+  )\r
+{\r
+  VARIABLE_STORE_TYPE     Type;\r
+  VARIABLE_POINTER_TRACK  Variable;\r
+  VARIABLE_POINTER_TRACK  VariableInHob;\r
+  VARIABLE_POINTER_TRACK  VariablePtrTrack;\r
+  UINTN                   VarNameSize;\r
+  EFI_STATUS              Status;\r
+  VARIABLE_STORE_HEADER   *VariableStoreHeader[VariableStoreTypeMax];\r
+\r
+  if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
+\r
+  Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
+  if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {\r
+    goto Done;\r
+  }\r
+\r
+  if (VariableName[0] != 0) {\r
+    //\r
+    // If variable name is not NULL, get next variable.\r
+    //\r
+    Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);\r
+  }\r
+\r
+  //\r
+  // 0: Volatile, 1: HOB, 2: Non-Volatile.\r
+  // The index and attributes mapping must be kept in this order as FindVariable\r
+  // makes use of this mapping to implement search algorithm.\r
+  //\r
+  VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;\r
+  VariableStoreHeader[VariableStoreTypeHob]      = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;\r
+  VariableStoreHeader[VariableStoreTypeNv]       = mNvVariableCache;\r
+\r
+  while (TRUE) {\r
+    //\r
+    // Switch from Volatile to HOB, to Non-Volatile.\r
+    //\r
+    while ((Variable.CurrPtr >= Variable.EndPtr) ||\r
+           (Variable.CurrPtr == NULL)            ||\r
+           !IsValidVariableHeader (Variable.CurrPtr)\r
+          ) {\r
+      //\r
+      // Find current storage index\r
+      //\r
+      for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {\r
+        if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) {\r
+          break;\r
+        }\r
+      }\r
+      ASSERT (Type < VariableStoreTypeMax);\r
+      //\r
+      // Switch to next storage\r
+      //\r
+      for (Type++; Type < VariableStoreTypeMax; Type++) {\r
+        if (VariableStoreHeader[Type] != NULL) {\r
+          break;\r
+        }\r
+      }\r
+      //\r
+      // Capture the case that \r
+      // 1. current storage is the last one, or\r
+      // 2. no further storage\r
+      //\r
+      if (Type == VariableStoreTypeMax) {\r
+        Status = EFI_NOT_FOUND;\r
+        goto Done;\r
+      }\r
+      Variable.StartPtr = GetStartPointer (VariableStoreHeader[Type]);\r
+      Variable.EndPtr   = GetEndPointer   (VariableStoreHeader[Type]);\r
+      Variable.CurrPtr  = Variable.StartPtr;\r
+    }\r
+\r
+    //\r
+    // Variable is found\r
+    //\r
+    if (Variable.CurrPtr->State == VAR_ADDED || Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
+      if (!AtRuntime () || ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {\r
+        if (Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
+          //\r
+          // If it is a IN_DELETED_TRANSITION variable,\r
+          // and there is also a same ADDED one at the same time,\r
+          // don't return it.\r
+          //\r
+          VariablePtrTrack.StartPtr = Variable.StartPtr;\r
+          VariablePtrTrack.EndPtr = Variable.EndPtr;\r
+          Status = FindVariableEx (\r
+                     GetVariableNamePtr (Variable.CurrPtr),\r
+                     &Variable.CurrPtr->VendorGuid,\r
+                     FALSE,\r
+                     &VariablePtrTrack\r
+                     );\r
+          if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State == VAR_ADDED) {\r
+            Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);\r
+            continue;\r
+          }\r
+        }\r
+\r
+        //\r
+        // Don't return NV variable when HOB overrides it\r
+        //\r
+        if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) && \r
+            (Variable.StartPtr == GetStartPointer (VariableStoreHeader[VariableStoreTypeNv]))\r
+           ) {\r
+          VariableInHob.StartPtr = GetStartPointer (VariableStoreHeader[VariableStoreTypeHob]);\r
+          VariableInHob.EndPtr   = GetEndPointer   (VariableStoreHeader[VariableStoreTypeHob]);\r
+          Status = FindVariableEx (\r
+                     GetVariableNamePtr (Variable.CurrPtr),\r
+                     &Variable.CurrPtr->VendorGuid,\r
+                     FALSE,\r
+                     &VariableInHob\r
+                     );\r
+          if (!EFI_ERROR (Status)) {\r
+            Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);\r
+            continue;\r
+          }\r
+        }\r
+\r
+        VarNameSize = NameSizeOfVariable (Variable.CurrPtr);\r
+        ASSERT (VarNameSize != 0);\r
+\r
+        if (VarNameSize <= *VariableNameSize) {\r
+          CopyMem (VariableName, GetVariableNamePtr (Variable.CurrPtr), VarNameSize);\r
+          CopyMem (VendorGuid, &Variable.CurrPtr->VendorGuid, sizeof (EFI_GUID));\r
+          Status = EFI_SUCCESS;\r
+        } else {\r
+          Status = EFI_BUFFER_TOO_SMALL;\r
+        }\r
+\r
+        *VariableNameSize = VarNameSize;\r
+        goto Done;\r
+      }\r
+    }\r
+\r
+    Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);\r
+  }\r
+\r
+Done:\r
+  ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
+  return Status;\r
+}\r
+\r
+/**\r
+\r
+  This code sets variable in storage blocks (Volatile or Non-Volatile).\r
+\r
+  @param VariableName                     Name of Variable to be found.\r
+  @param VendorGuid                       Variable vendor GUID.\r
+  @param Attributes                       Attribute value of the variable found\r
+  @param DataSize                         Size of Data found. If size is less than the\r
+                                          data, this value contains the required size.\r
+  @param Data                             Data pointer.\r
+\r
+  @return EFI_INVALID_PARAMETER           Invalid parameter.\r
+  @return EFI_SUCCESS                     Set successfully.\r
+  @return EFI_OUT_OF_RESOURCES            Resource not enough to set variable.\r
+  @return EFI_NOT_FOUND                   Not found.\r
+  @return EFI_WRITE_PROTECTED             Variable is read-only.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+VariableServiceSetVariable (\r
+  IN CHAR16                  *VariableName,\r
+  IN EFI_GUID                *VendorGuid,\r
+  IN UINT32                  Attributes,\r
+  IN UINTN                   DataSize,\r
+  IN VOID                    *Data\r
+  )\r
+{\r
+  VARIABLE_POINTER_TRACK              Variable;\r
+  EFI_STATUS                          Status;\r
+  VARIABLE_HEADER                     *NextVariable;\r
+  EFI_PHYSICAL_ADDRESS                Point;\r
+  LIST_ENTRY                          *Link;\r
+  VARIABLE_ENTRY                      *Entry;\r
+\r
+  //\r
+  // Check input parameters.\r
+  //\r
+  if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  } \r
+\r
+  if (DataSize != 0 && Data == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  // Not support authenticated or append variable write yet.\r
+  //\r
+  if ((Attributes & (EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_APPEND_WRITE)) != 0) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  //  Make sure if runtime bit is set, boot service bit is set also.\r
+  //\r
+  if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if ((UINTN)(~0) - DataSize < StrSize(VariableName)){\r
+    //\r
+    // Prevent whole variable size overflow \r
+    // \r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  //  The size of the VariableName, including the Unicode Null in bytes plus\r
+  //  the DataSize is limited to maximum size of PcdGet32 (PcdMaxHardwareErrorVariableSize)\r
+  //  bytes for HwErrRec, and PcdGet32 (PcdMaxVariableSize) bytes for the others.\r
+  //\r
+  if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+    if ( StrSize (VariableName) + DataSize > PcdGet32 (PcdMaxHardwareErrorVariableSize) - sizeof (VARIABLE_HEADER)) {\r
+      return EFI_INVALID_PARAMETER;\r
+    }\r
+    if (!IsHwErrRecVariable(VariableName, VendorGuid)) {\r
+      return EFI_INVALID_PARAMETER;\r
+    }\r
+  } else {\r
+    //\r
+    //  The size of the VariableName, including the Unicode Null in bytes plus\r
+    //  the DataSize is limited to maximum size of PcdGet32 (PcdMaxVariableSize) bytes.\r
+    //\r
+    if (StrSize (VariableName) + DataSize > PcdGet32 (PcdMaxVariableSize) - sizeof (VARIABLE_HEADER)) {\r
+      return EFI_INVALID_PARAMETER;\r
+    }  \r
+  }\r
+\r
+  Status = CheckEfiGlobalVariable (VariableName, VendorGuid, Attributes);\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+\r
+  AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
+\r
+  //\r
+  // Consider reentrant in MCA/INIT/NMI. It needs be reupdated.\r
+  //\r
+  if (1 < InterlockedIncrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState)) {\r
+    Point = mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;\r
+    //\r
+    // Parse non-volatile variable data and get last variable offset.\r
+    //\r
+    NextVariable  = GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point);\r
+    while ((NextVariable < GetEndPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point)) \r
+        && IsValidVariableHeader (NextVariable)) {\r
+      NextVariable = GetNextVariablePtr (NextVariable);\r
+    }\r
+    mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) Point;\r
+  }\r
+\r
+  if (mEndOfDxe && mEnableLocking) {\r
+    //\r
+    // Treat the variables listed in the forbidden variable list as read-only after leaving DXE phase.\r
+    //\r
+    for ( Link = GetFirstNode (&mLockedVariableList)\r
+        ; !IsNull (&mLockedVariableList, Link)\r
+        ; Link = GetNextNode (&mLockedVariableList, Link)\r
+        ) {\r
+      Entry = BASE_CR (Link, VARIABLE_ENTRY, Link);\r
+      if (CompareGuid (&Entry->Guid, VendorGuid) && (StrCmp (Entry->Name, VariableName) == 0)) {\r
+        Status = EFI_WRITE_PROTECTED;\r
+        DEBUG ((EFI_D_INFO, "[Variable]: Changing readonly variable after leaving DXE phase - %g:%s\n", VendorGuid, VariableName));\r
+        goto Done;\r
+      }\r
+    }\r
+  }\r
+\r
+  //\r
+  // Check whether the input variable is already existed.\r
+  //\r
+  Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, TRUE);\r
+  if (!EFI_ERROR (Status)) {\r
+    if (((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) && AtRuntime ()) {\r
+      Status = EFI_WRITE_PROTECTED;\r
+      goto Done;\r
+    }\r
+    if (Attributes != 0 && Attributes != Variable.CurrPtr->Attributes) {\r
+      //\r
+      // If a preexisting variable is rewritten with different attributes, SetVariable() shall not\r
+      // modify the variable and shall return EFI_INVALID_PARAMETER. Two exceptions to this rule:\r
+      // 1. No access attributes specified\r
+      // 2. The only attribute differing is EFI_VARIABLE_APPEND_WRITE\r
+      //\r
+      Status = EFI_INVALID_PARAMETER;\r
+      goto Done;\r
+    }\r
+  }\r
+\r
+  if (!FeaturePcdGet (PcdUefiVariableDefaultLangDeprecate)) {\r
+    //\r
+    // Hook the operation of setting PlatformLangCodes/PlatformLang and LangCodes/Lang.\r
+    //\r
+    Status = AutoUpdateLangVariable (VariableName, Data, DataSize);\r
+    if (EFI_ERROR (Status)) {\r
+      //\r
+      // The auto update operation failed, directly return to avoid inconsistency between PlatformLang and Lang.\r
+      //\r
+      goto Done;\r
+    }\r
+  }\r
+\r
+  Status = UpdateVariable (VariableName, VendorGuid, Data, DataSize, Attributes, &Variable);\r
+\r
+Done:\r
+  InterlockedDecrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState);\r
+  ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
+\r
+  return Status;\r
+}\r
+\r
+/**\r
+\r
+  This code returns information about the EFI variables.\r
+\r
+  @param Attributes                     Attributes bitmask to specify the type of variables\r
+                                        on which to return information.\r
+  @param MaximumVariableStorageSize     Pointer to the maximum size of the storage space available\r
+                                        for the EFI variables associated with the attributes specified.\r
+  @param RemainingVariableStorageSize   Pointer to the remaining size of the storage space available\r
+                                        for EFI variables associated with the attributes specified.\r
+  @param MaximumVariableSize            Pointer to the maximum size of an individual EFI variables\r
+                                        associated with the attributes specified.\r
+\r
+  @return EFI_SUCCESS                   Query successfully.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+VariableServiceQueryVariableInfoInternal (\r
+  IN  UINT32                 Attributes,\r
+  OUT UINT64                 *MaximumVariableStorageSize,\r
+  OUT UINT64                 *RemainingVariableStorageSize,\r
+  OUT UINT64                 *MaximumVariableSize\r
+  )\r
+{\r
+  VARIABLE_HEADER        *Variable;\r
+  VARIABLE_HEADER        *NextVariable;\r
+  UINT64                 VariableSize;\r
+  VARIABLE_STORE_HEADER  *VariableStoreHeader;\r
+  UINT64                 CommonVariableTotalSize;\r
+  UINT64                 HwErrVariableTotalSize;\r
+  EFI_STATUS             Status;\r
+  VARIABLE_POINTER_TRACK VariablePtrTrack;\r
+\r
+  CommonVariableTotalSize = 0;\r
+  HwErrVariableTotalSize = 0;\r
+\r
+  if((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {\r
+    //\r
+    // Query is Volatile related.\r
+    //\r
+    VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);\r
+  } else {\r
+    //\r
+    // Query is Non-Volatile related.\r
+    //\r
+    VariableStoreHeader = mNvVariableCache;\r
+  }\r
+\r
+  //\r
+  // Now let's fill *MaximumVariableStorageSize *RemainingVariableStorageSize\r
+  // with the storage size (excluding the storage header size).\r
+  //\r
+  *MaximumVariableStorageSize   = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER);\r
+\r
+  //\r
+  // Harware error record variable needs larger size.\r
+  //\r
+  if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {\r
+    *MaximumVariableStorageSize = PcdGet32 (PcdHwErrStorageSize);\r
+    *MaximumVariableSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - sizeof (VARIABLE_HEADER);\r
+  } else {\r
+    if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {\r
+      ASSERT (PcdGet32 (PcdHwErrStorageSize) < VariableStoreHeader->Size);\r
+      *MaximumVariableStorageSize = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize);\r
+    }\r
+\r
+    //\r
+    // Let *MaximumVariableSize be PcdGet32 (PcdMaxVariableSize) with the exception of the variable header size.\r
+    //\r
+    *MaximumVariableSize = PcdGet32 (PcdMaxVariableSize) - sizeof (VARIABLE_HEADER);\r
+  }\r
+\r
+  //\r
+  // Point to the starting address of the variables.\r
+  //\r
+  Variable = GetStartPointer (VariableStoreHeader);\r
+\r
+  //\r
+  // Now walk through the related variable store.\r
+  //\r
+  while ((Variable < GetEndPointer (VariableStoreHeader)) && IsValidVariableHeader (Variable)) {\r
+    NextVariable = GetNextVariablePtr (Variable);\r
+    VariableSize = (UINT64) (UINTN) NextVariable - (UINT64) (UINTN) Variable;\r
+\r
+    if (AtRuntime ()) {\r
+      //\r
+      // We don't take the state of the variables in mind\r
+      // when calculating RemainingVariableStorageSize,\r
+      // since the space occupied by variables not marked with\r
+      // VAR_ADDED is not allowed to be reclaimed in Runtime.\r
+      //\r
+      if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+        HwErrVariableTotalSize += VariableSize;\r
+      } else {\r
+        CommonVariableTotalSize += VariableSize;\r
+      }\r
+    } else {\r
+      //\r
+      // Only care about Variables with State VAR_ADDED, because\r
+      // the space not marked as VAR_ADDED is reclaimable now.\r
+      //\r
+      if (Variable->State == VAR_ADDED) {\r
+        if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+          HwErrVariableTotalSize += VariableSize;\r
+        } else {\r
+          CommonVariableTotalSize += VariableSize;\r
+        }\r
+      } else if (Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
+        //\r
+        // If it is a IN_DELETED_TRANSITION variable,\r
+        // and there is not also a same ADDED one at the same time,\r
+        // this IN_DELETED_TRANSITION variable is valid.\r
+        //\r
+        VariablePtrTrack.StartPtr = GetStartPointer (VariableStoreHeader);\r
+        VariablePtrTrack.EndPtr   = GetEndPointer   (VariableStoreHeader);\r
+        Status = FindVariableEx (\r
+                   GetVariableNamePtr (Variable),\r
+                   &Variable->VendorGuid,\r
+                   FALSE,\r
+                   &VariablePtrTrack\r
+                   );\r
+        if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State != VAR_ADDED) {\r
+          if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+            HwErrVariableTotalSize += VariableSize;\r
+          } else {\r
+            CommonVariableTotalSize += VariableSize;\r
+          }\r
+        }\r
+      }\r
+    }\r
+\r
+    //\r
+    // Go to the next one.\r
+    //\r
+    Variable = NextVariable;\r
+  }\r
+\r
+  if ((Attributes  & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD){\r
+    *RemainingVariableStorageSize = *MaximumVariableStorageSize - HwErrVariableTotalSize;\r
+  }else {\r
+    *RemainingVariableStorageSize = *MaximumVariableStorageSize - CommonVariableTotalSize;\r
+  }\r
+\r
+  if (*RemainingVariableStorageSize < sizeof (VARIABLE_HEADER)) {\r
+    *MaximumVariableSize = 0;\r
+  } else if ((*RemainingVariableStorageSize - sizeof (VARIABLE_HEADER)) < *MaximumVariableSize) {\r
+    *MaximumVariableSize = *RemainingVariableStorageSize - sizeof (VARIABLE_HEADER);\r
+  }\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+/**\r
+\r
+  This code returns information about the EFI variables.\r
+\r
+  @param Attributes                     Attributes bitmask to specify the type of variables\r
+                                        on which to return information.\r
+  @param MaximumVariableStorageSize     Pointer to the maximum size of the storage space available\r
+                                        for the EFI variables associated with the attributes specified.\r
+  @param RemainingVariableStorageSize   Pointer to the remaining size of the storage space available\r
+                                        for EFI variables associated with the attributes specified.\r
+  @param MaximumVariableSize            Pointer to the maximum size of an individual EFI variables\r
+                                        associated with the attributes specified.\r
+\r
+  @return EFI_INVALID_PARAMETER         An invalid combination of attribute bits was supplied.\r
+  @return EFI_SUCCESS                   Query successfully.\r
+  @return EFI_UNSUPPORTED               The attribute is not supported on this platform.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+VariableServiceQueryVariableInfo (\r
+  IN  UINT32                 Attributes,\r
+  OUT UINT64                 *MaximumVariableStorageSize,\r
+  OUT UINT64                 *RemainingVariableStorageSize,\r
+  OUT UINT64                 *MaximumVariableSize\r
+  )\r
+{\r
+  EFI_STATUS             Status;\r
+\r
+  if(MaximumVariableStorageSize == NULL || RemainingVariableStorageSize == NULL || MaximumVariableSize == NULL || Attributes == 0) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == 0) {\r
+    //\r
+    // Make sure the Attributes combination is supported by the platform.\r
+    //\r
+    return EFI_UNSUPPORTED;\r
+  } else if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {\r
+    //\r
+    // Make sure if runtime bit is set, boot service bit is set also.\r
+    //\r
+    return EFI_INVALID_PARAMETER;\r
+  } else if (AtRuntime () && ((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) {\r
+    //\r
+    // Make sure RT Attribute is set if we are in Runtime phase.\r
+    //\r
+    return EFI_INVALID_PARAMETER;\r
+  } else if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+    //\r
+    // Make sure Hw Attribute is set with NV.\r
+    //\r
+    return EFI_INVALID_PARAMETER;\r
+  } else if ((Attributes & (EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_APPEND_WRITE)) != 0) {\r
+    //\r
+    // Not support authenticated or append variable write yet.\r
+    //\r
+    return EFI_UNSUPPORTED;\r
+  }\r
+\r
+  AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
+\r
+  Status = VariableServiceQueryVariableInfoInternal (\r
+             Attributes,\r
+             MaximumVariableStorageSize,\r
+             RemainingVariableStorageSize,\r
+             MaximumVariableSize\r
+             );\r
+\r
+  ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
+  return Status;\r
+}\r
+\r
+/**\r
+  This function reclaims variable storage if free size is below the threshold.\r
+  \r
+**/\r
+VOID\r
+ReclaimForOS(\r
+  VOID\r
+  )\r
+{\r
+  EFI_STATUS                     Status;\r
+  UINTN                          CommonVariableSpace;\r
+  UINTN                          RemainingCommonVariableSpace;\r
+  UINTN                          RemainingHwErrVariableSpace;\r
+\r
+  Status  = EFI_SUCCESS; \r
+\r
+  CommonVariableSpace = ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase)))->Size - sizeof (VARIABLE_STORE_HEADER) - PcdGet32(PcdHwErrStorageSize); //Allowable max size of common variable storage space\r
+\r
+  RemainingCommonVariableSpace = CommonVariableSpace - mVariableModuleGlobal->CommonVariableTotalSize;\r
+\r
+  RemainingHwErrVariableSpace = PcdGet32 (PcdHwErrStorageSize) - mVariableModuleGlobal->HwErrVariableTotalSize;\r
+  //\r
+  // Check if the free area is blow a threshold.\r
+  //\r
+  if ((RemainingCommonVariableSpace < PcdGet32 (PcdMaxVariableSize))\r
+    || ((PcdGet32 (PcdHwErrStorageSize) != 0) && \r
+       (RemainingHwErrVariableSpace < PcdGet32 (PcdMaxHardwareErrorVariableSize)))){\r
+    Status = Reclaim (\r
+            mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,\r
+            &mVariableModuleGlobal->NonVolatileLastVariableOffset,\r
+            FALSE,\r
+            NULL,\r
+            NULL,\r
+            0\r
+            );\r
+    ASSERT_EFI_ERROR (Status);\r
+  }\r
+}\r
+\r
+/**\r
+  Init non-volatile variable store.\r
+\r
+  @retval EFI_SUCCESS           Function successfully executed.\r
+  @retval EFI_OUT_OF_RESOURCES  Fail to allocate enough memory resource.\r
+  @retval EFI_VOLUME_CORRUPTED  Variable Store or Firmware Volume for Variable Store is corrupted.\r
+\r
+**/\r
+EFI_STATUS\r
+InitNonVolatileVariableStore (\r
+  VOID\r
   )\r
 {\r
-  VARIABLE_HEADER        *Variable;\r
-  VARIABLE_HEADER        *NextVariable;\r
-  UINT64                 VariableSize;\r
-  VARIABLE_STORE_HEADER  *VariableStoreHeader;\r
+  EFI_FIRMWARE_VOLUME_HEADER            *FvHeader;\r
+  VARIABLE_HEADER                       *NextVariable;\r
+  EFI_PHYSICAL_ADDRESS                  VariableStoreBase;\r
+  UINT64                                VariableStoreLength;\r
+  UINTN                                 VariableSize;\r
+  EFI_HOB_GUID_TYPE                     *GuidHob;\r
+  EFI_PHYSICAL_ADDRESS                  NvStorageBase;\r
+  UINT8                                 *NvStorageData;\r
+  UINT32                                NvStorageSize;\r
+  FAULT_TOLERANT_WRITE_LAST_WRITE_DATA  *FtwLastWriteData;\r
+  UINT32                                BackUpOffset;\r
+  UINT32                                BackUpSize;\r
 \r
-  if(MaximumVariableStorageSize == NULL || RemainingVariableStorageSize == NULL || MaximumVariableSize == NULL || Attributes == 0) {\r
-    return EFI_INVALID_PARAMETER;\r
-  }\r
-  \r
-  if((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == 0) {\r
-    //\r
-    // Make sure the Attributes combination is supported by the platform.\r
-    //\r
-    return EFI_UNSUPPORTED;  \r
-  } else if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {\r
-    //\r
-    // Make sure if runtime bit is set, boot service bit is set also.\r
-    //\r
-    return EFI_INVALID_PARAMETER;\r
-  } else if (EfiAtRuntime () && ((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) {\r
-    //\r
-    // Make sure RT Attribute is set if we are in Runtime phase.\r
-    //\r
-    return EFI_INVALID_PARAMETER;\r
-  }\r
+  mVariableModuleGlobal->FvbInstance = NULL;\r
 \r
-  AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
+  //\r
+  // Note that in EdkII variable driver implementation, Hardware Error Record type variable\r
+  // is stored with common variable in the same NV region. So the platform integrator should\r
+  // ensure that the value of PcdHwErrStorageSize is less than or equal to the value of\r
+  // PcdFlashNvStorageVariableSize.\r
+  //\r
+  ASSERT (PcdGet32 (PcdHwErrStorageSize) <= PcdGet32 (PcdFlashNvStorageVariableSize));\r
 \r
-  if((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {\r
-    //\r
-    // Query is Volatile related.\r
-    //\r
-    VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);\r
-  } else {\r
-    //\r
-    // Query is Non-Volatile related.\r
-    //\r
-    VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase);\r
+  //\r
+  // Allocate runtime memory used for a memory copy of the FLASH region.\r
+  // Keep the memory and the FLASH in sync as updates occur.\r
+  //\r
+  NvStorageSize = PcdGet32 (PcdFlashNvStorageVariableSize);\r
+  NvStorageData = AllocateRuntimeZeroPool (NvStorageSize);\r
+  if (NvStorageData == NULL) {\r
+    return EFI_OUT_OF_RESOURCES;\r
   }\r
 \r
+  NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageVariableBase64);\r
+  if (NvStorageBase == 0) {\r
+    NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageVariableBase);\r
+  }\r
   //\r
-  // Now let's fill *MaximumVariableStorageSize *RemainingVariableStorageSize\r
-  // with the storage size (excluding the storage header size).\r
+  // Copy NV storage data to the memory buffer.\r
   //\r
-  *MaximumVariableStorageSize   = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER);\r
-  *RemainingVariableStorageSize = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER);\r
+  CopyMem (NvStorageData, (UINT8 *) (UINTN) NvStorageBase, NvStorageSize);\r
 \r
   //\r
-  // Let *MaximumVariableSize be FixedPcdGet32(PcdMaxVariableSize) with the exception of the variable header size.\r
+  // Check the FTW last write data hob.\r
   //\r
-  *MaximumVariableSize = FixedPcdGet32(PcdMaxVariableSize) - sizeof (VARIABLE_HEADER);\r
+  GuidHob = GetFirstGuidHob (&gEdkiiFaultTolerantWriteGuid);\r
+  if (GuidHob != NULL) {\r
+    FtwLastWriteData = (FAULT_TOLERANT_WRITE_LAST_WRITE_DATA *) GET_GUID_HOB_DATA (GuidHob);\r
+    if (FtwLastWriteData->TargetAddress == NvStorageBase) {\r
+      DEBUG ((EFI_D_INFO, "Variable: NV storage is backed up in spare block: 0x%x\n", (UINTN) FtwLastWriteData->SpareAddress));\r
+      //\r
+      // Copy the backed up NV storage data to the memory buffer from spare block.\r
+      //\r
+      CopyMem (NvStorageData, (UINT8 *) (UINTN) (FtwLastWriteData->SpareAddress), NvStorageSize);\r
+    } else if ((FtwLastWriteData->TargetAddress > NvStorageBase) &&\r
+               (FtwLastWriteData->TargetAddress < (NvStorageBase + NvStorageSize))) {\r
+      //\r
+      // Flash NV storage from the offset is backed up in spare block.\r
+      //\r
+      BackUpOffset = (UINT32) (FtwLastWriteData->TargetAddress - NvStorageBase);\r
+      BackUpSize = NvStorageSize - BackUpOffset;\r
+      DEBUG ((EFI_D_INFO, "Variable: High partial NV storage from offset: %x is backed up in spare block: 0x%x\n", BackUpOffset, (UINTN) FtwLastWriteData->SpareAddress));\r
+      //\r
+      // Copy the partial backed up NV storage data to the memory buffer from spare block.\r
+      //\r
+      CopyMem (NvStorageData + BackUpOffset, (UINT8 *) (UINTN) FtwLastWriteData->SpareAddress, BackUpSize);\r
+    }\r
+  }\r
+\r
+  FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *) NvStorageData;\r
 \r
   //\r
-  // Harware error record variable needs larger size.\r
+  // Check if the Firmware Volume is not corrupted\r
   //\r
-  if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
-    *MaximumVariableSize = FixedPcdGet32(PcdMaxHardwareErrorVariableSize) - sizeof (VARIABLE_HEADER);\r
+  if ((FvHeader->Signature != EFI_FVH_SIGNATURE) || (!CompareGuid (&gEfiSystemNvDataFvGuid, &FvHeader->FileSystemGuid))) {\r
+    FreePool (NvStorageData);\r
+    DEBUG ((EFI_D_ERROR, "Firmware Volume for Variable Store is corrupted\n"));\r
+    return EFI_VOLUME_CORRUPTED;\r
+  }\r
+\r
+  VariableStoreBase = (EFI_PHYSICAL_ADDRESS) ((UINTN) FvHeader + FvHeader->HeaderLength);\r
+  VariableStoreLength = (UINT64) (NvStorageSize - FvHeader->HeaderLength);\r
+\r
+  mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;\r
+  mNvVariableCache = (VARIABLE_STORE_HEADER *) (UINTN) VariableStoreBase;\r
+  if (GetVariableStoreStatus (mNvVariableCache) != EfiValid) {\r
+    FreePool (NvStorageData);\r
+    DEBUG((EFI_D_ERROR, "Variable Store header is corrupted\n"));\r
+    return EFI_VOLUME_CORRUPTED;\r
   }\r
+  ASSERT(mNvVariableCache->Size == VariableStoreLength);\r
 \r
   //\r
-  // Point to the starting address of the variables.\r
+  // The max variable or hardware error variable size should be < variable store size.\r
   //\r
-  Variable = GetStartPointer (VariableStoreHeader);\r
+  ASSERT(MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize)) < VariableStoreLength);\r
 \r
   //\r
-  // Now walk through the related variable store.\r
+  // Parse non-volatile variable data and get last variable offset.\r
   //\r
-  while (IsValidVariableHeader (Variable) && (Variable < GetEndPointer (VariableStoreHeader))) {\r
-    NextVariable = GetNextVariablePtr (Variable);\r
-    VariableSize = (UINT64) (UINTN) NextVariable - (UINT64) (UINTN) Variable;\r
+  NextVariable  = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase);\r
+  while (IsValidVariableHeader (NextVariable)) {\r
+    VariableSize = NextVariable->NameSize + NextVariable->DataSize + sizeof (VARIABLE_HEADER);\r
+    if ((NextVariable->Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {\r
+      mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VariableSize);\r
+    } else {\r
+      mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VariableSize);\r
+    }\r
+\r
+    NextVariable = GetNextVariablePtr (NextVariable);\r
+  }\r
+  mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) VariableStoreBase;\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+/**\r
+  Flush the HOB variable to flash.\r
+\r
+  @param[in] VariableName       Name of variable has been updated or deleted.\r
+  @param[in] VendorGuid         Guid of variable has been updated or deleted.\r
+\r
+**/\r
+VOID\r
+FlushHobVariableToFlash (\r
+  IN CHAR16                     *VariableName,\r
+  IN EFI_GUID                   *VendorGuid\r
+  )\r
+{\r
+  EFI_STATUS                    Status;\r
+  VARIABLE_STORE_HEADER         *VariableStoreHeader;\r
+  VARIABLE_HEADER               *Variable;\r
+  VOID                          *VariableData;\r
+  BOOLEAN                       ErrorFlag;\r
+\r
+  ErrorFlag = FALSE;\r
 \r
-    if (EfiAtRuntime ()) {\r
+  //\r
+  // Flush the HOB variable to flash.\r
+  //\r
+  if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {\r
+    VariableStoreHeader = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;\r
+    //\r
+    // Set HobVariableBase to 0, it can avoid SetVariable to call back.\r
+    //\r
+    mVariableModuleGlobal->VariableGlobal.HobVariableBase = 0;\r
+    for ( Variable = GetStartPointer (VariableStoreHeader)\r
+        ; (Variable < GetEndPointer (VariableStoreHeader) && IsValidVariableHeader (Variable))\r
+        ; Variable = GetNextVariablePtr (Variable)\r
+        ) {\r
+      if (Variable->State != VAR_ADDED) {\r
+        //\r
+        // The HOB variable has been set to DELETED state in local.\r
+        //\r
+        continue;\r
+      }\r
+      ASSERT ((Variable->Attributes & EFI_VARIABLE_NON_VOLATILE) != 0);\r
+      if (VendorGuid == NULL || VariableName == NULL ||\r
+          !CompareGuid (VendorGuid, &Variable->VendorGuid) ||\r
+          StrCmp (VariableName, GetVariableNamePtr (Variable)) != 0) {\r
+        VariableData = GetVariableDataPtr (Variable);\r
+        Status = VariableServiceSetVariable (\r
+                   GetVariableNamePtr (Variable),\r
+                   &Variable->VendorGuid,\r
+                   Variable->Attributes,\r
+                   Variable->DataSize,\r
+                   VariableData\r
+                   );\r
+        DEBUG ((EFI_D_INFO, "Variable driver flush the HOB variable to flash: %g %s %r\n", &Variable->VendorGuid, GetVariableNamePtr (Variable), Status));\r
+      } else {\r
+        //\r
+        // The updated or deleted variable is matched with the HOB variable.\r
+        // Don't break here because we will try to set other HOB variables\r
+        // since this variable could be set successfully.\r
+        //\r
+        Status = EFI_SUCCESS;\r
+      }\r
+      if (!EFI_ERROR (Status)) {\r
+        //\r
+        // If set variable successful, or the updated or deleted variable is matched with the HOB variable,\r
+        // set the HOB variable to DELETED state in local.\r
+        //\r
+        DEBUG ((EFI_D_INFO, "Variable driver set the HOB variable to DELETED state in local: %g %s\n", &Variable->VendorGuid, GetVariableNamePtr (Variable)));\r
+        Variable->State &= VAR_DELETED;\r
+      } else {\r
+        ErrorFlag = TRUE;\r
+      }\r
+    }\r
+    if (ErrorFlag) {\r
       //\r
-      // we don't take the state of the variables in mind\r
-      // when calculating RemainingVariableStorageSize,\r
-      // since the space occupied by variables not marked with\r
-      // VAR_ADDED is not allowed to be reclaimed in Runtime.\r
+      // We still have HOB variable(s) not flushed in flash.\r
       //\r
-      *RemainingVariableStorageSize -= VariableSize;\r
+      mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStoreHeader;\r
     } else {\r
       //\r
-      // Only care about Variables with State VAR_ADDED,because\r
-      // the space not marked as VAR_ADDED is reclaimable now.\r
+      // All HOB variables have been flushed in flash.\r
       //\r
-      if (Variable->State == VAR_ADDED) {\r
-        *RemainingVariableStorageSize -= VariableSize;\r
+      DEBUG ((EFI_D_INFO, "Variable driver: all HOB variables have been flushed in flash.\n"));\r
+      if (!AtRuntime ()) {\r
+        FreePool ((VOID *) VariableStoreHeader);\r
       }\r
     }\r
-\r
-    //\r
-    // Go to the next one\r
-    //\r
-    Variable = NextVariable;\r
-  }\r
-\r
-  if (*RemainingVariableStorageSize < sizeof (VARIABLE_HEADER)) {\r
-    *MaximumVariableSize = 0;\r
-  } else if ((*RemainingVariableStorageSize - sizeof (VARIABLE_HEADER)) < *MaximumVariableSize) {\r
-    *MaximumVariableSize = *RemainingVariableStorageSize - sizeof (VARIABLE_HEADER);\r
   }\r
 \r
-  ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
-  return EFI_SUCCESS;\r
 }\r
 \r
-\r
 /**\r
-  Notification function of EVT_GROUP_READY_TO_BOOT event group.\r
+  Initializes variable write service after FTW was ready.\r
 \r
-  This is a notification function registered on EVT_GROUP_READY_TO_BOOT event group.\r
-  When the Boot Manager is about to load and execute a boot option, it reclaims variable\r
-  storage if free size is below the threshold.\r
-\r
-  @param  Event        Event whose notification function is being invoked\r
-  @param  Context      Pointer to the notification function's context\r
+  @retval EFI_SUCCESS          Function successfully executed.\r
+  @retval Others               Fail to initialize the variable service.\r
 \r
 **/\r
-VOID\r
-EFIAPI\r
-ReclaimForOS(\r
-  EFI_EVENT  Event,\r
-  VOID       *Context\r
+EFI_STATUS\r
+VariableWriteServiceInitialize (\r
+  VOID\r
   )\r
 {\r
-  UINT32                          VarSize;\r
   EFI_STATUS                      Status;\r
+  VARIABLE_STORE_HEADER           *VariableStoreHeader;\r
+  UINTN                           Index;\r
+  UINT8                           Data;\r
+  EFI_PHYSICAL_ADDRESS            VariableStoreBase;\r
+  EFI_PHYSICAL_ADDRESS            NvStorageBase;\r
 \r
-  VarSize = ((VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase))->Size;\r
-  Status  = EFI_SUCCESS; \r
+  NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageVariableBase64);\r
+  if (NvStorageBase == 0) {\r
+    NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageVariableBase);\r
+  }\r
+  VariableStoreBase = NvStorageBase + (((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(NvStorageBase))->HeaderLength);\r
 \r
   //\r
-  // Check if the free area is blow a threshold\r
+  // Let NonVolatileVariableBase point to flash variable store base directly after FTW ready.\r
   //\r
-  if ((VarSize - mVariableModuleGlobal->NonVolatileLastVariableOffset) < VARIABLE_RECLAIM_THRESHOLD) {\r
-    Status = Reclaim (\r
-              mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,\r
-              &mVariableModuleGlobal->NonVolatileLastVariableOffset,\r
-              FALSE,\r
-              NULL\r
-              );\r
-    ASSERT_EFI_ERROR (Status);\r
+  mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;\r
+  VariableStoreHeader = (VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase;\r
\r
+  //\r
+  // Check if the free area is really free.\r
+  //\r
+  for (Index = mVariableModuleGlobal->NonVolatileLastVariableOffset; Index < VariableStoreHeader->Size; Index++) {\r
+    Data = ((UINT8 *) mNvVariableCache)[Index];\r
+    if (Data != 0xff) {\r
+      //\r
+      // There must be something wrong in variable store, do reclaim operation.\r
+      //\r
+      Status = Reclaim (\r
+                 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,\r
+                 &mVariableModuleGlobal->NonVolatileLastVariableOffset,\r
+                 FALSE,\r
+                 NULL,\r
+                 NULL,\r
+                 0\r
+                 );\r
+      if (EFI_ERROR (Status)) {\r
+        return Status;\r
+      }\r
+      break;\r
+    }\r
   }\r
+\r
+  FlushHobVariableToFlash (NULL, NULL);\r
+\r
+  return EFI_SUCCESS;\r
 }\r
 \r
+\r
 /**\r
   Initializes variable store area for non-volatile and volatile variable.\r
 \r
-  @param  ImageHandle           The Image handle of this driver.\r
-  @param  SystemTable           The pointer of EFI_SYSTEM_TABLE.\r
-\r
   @retval EFI_SUCCESS           Function successfully executed.\r
   @retval EFI_OUT_OF_RESOURCES  Fail to allocate enough memory resource.\r
 \r
 **/\r
 EFI_STATUS\r
 VariableCommonInitialize (\r
-  IN EFI_HANDLE         ImageHandle,\r
-  IN EFI_SYSTEM_TABLE   *SystemTable\r
+  VOID\r
   )\r
 {\r
   EFI_STATUS                      Status;\r
-  EFI_FIRMWARE_VOLUME_HEADER      *FwVolHeader;\r
-  CHAR8                           *CurrPtr;\r
   VARIABLE_STORE_HEADER           *VolatileVariableStore;\r
   VARIABLE_STORE_HEADER           *VariableStoreHeader;\r
-  VARIABLE_HEADER                 *NextVariable;\r
-  UINT32                          Instance;\r
-  EFI_PHYSICAL_ADDRESS            FvVolHdr;\r
-  UINT64                          TempVariableStoreHeader;\r
-  EFI_GCD_MEMORY_SPACE_DESCRIPTOR GcdDescriptor;\r
-  UINT64                          BaseAddress;\r
-  UINT64                          Length;\r
-  UINTN                           Index;\r
-  UINT8                           Data;\r
-  UINT64                          VariableStoreBase;\r
   UINT64                          VariableStoreLength;\r
-  EFI_EVENT                       ReadyToBootEvent;\r
+  UINTN                           ScratchSize;\r
+  EFI_HOB_GUID_TYPE               *GuidHob;\r
 \r
-  Status = EFI_SUCCESS;\r
   //\r
   // Allocate runtime memory for variable driver global structure.\r
   //\r
-  mVariableModuleGlobal = AllocateRuntimePool (sizeof (VARIABLE_MODULE_GLOBAL));\r
+  mVariableModuleGlobal = AllocateRuntimeZeroPool (sizeof (VARIABLE_MODULE_GLOBAL));\r
   if (mVariableModuleGlobal == NULL) {\r
     return EFI_OUT_OF_RESOURCES;\r
   }\r
 \r
-  EfiInitializeLock(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock, TPL_NOTIFY);\r
-  mVariableModuleGlobal->VariableGlobal.ReentrantState = 0;\r
+  InitializeLock (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock, TPL_NOTIFY);\r
+\r
+  //\r
+  // Get HOB variable store.\r
+  //\r
+  GuidHob = GetFirstGuidHob (&gEfiVariableGuid);\r
+  if (GuidHob != NULL) {\r
+    VariableStoreHeader = GET_GUID_HOB_DATA (GuidHob);\r
+    VariableStoreLength = (UINT64) (GuidHob->Header.HobLength - sizeof (EFI_HOB_GUID_TYPE));\r
+    if (GetVariableStoreStatus (VariableStoreHeader) == EfiValid) {\r
+      mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) AllocateRuntimeCopyPool ((UINTN) VariableStoreLength, (VOID *) VariableStoreHeader);\r
+      if (mVariableModuleGlobal->VariableGlobal.HobVariableBase == 0) {\r
+        FreePool (mVariableModuleGlobal);\r
+        return EFI_OUT_OF_RESOURCES;\r
+      }\r
+    } else {\r
+      DEBUG ((EFI_D_ERROR, "HOB Variable Store header is corrupted!\n"));\r
+    }\r
+  }\r
 \r
   //\r
-  // Allocate memory for volatile variable store\r
+  // Allocate memory for volatile variable store, note that there is a scratch space to store scratch data.\r
   //\r
-  VolatileVariableStore = AllocateRuntimePool (FixedPcdGet32(PcdVariableStoreSize) + FixedPcdGet32(PcdMaxVariableSize));\r
+  ScratchSize = MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize));\r
+  VolatileVariableStore = AllocateRuntimePool (PcdGet32 (PcdVariableStoreSize) + ScratchSize);\r
   if (VolatileVariableStore == NULL) {\r
+    if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {\r
+      FreePool ((VOID *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase);\r
+    }\r
     FreePool (mVariableModuleGlobal);\r
     return EFI_OUT_OF_RESOURCES;\r
   }\r
 \r
-  SetMem (VolatileVariableStore, FixedPcdGet32(PcdVariableStoreSize) + FixedPcdGet32(PcdMaxVariableSize), 0xff);\r
+  SetMem (VolatileVariableStore, PcdGet32 (PcdVariableStoreSize) + ScratchSize, 0xff);\r
 \r
   //\r
-  //  Variable Specific Data\r
+  // Initialize Variable Specific Data.\r
   //\r
   mVariableModuleGlobal->VariableGlobal.VolatileVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VolatileVariableStore;\r
   mVariableModuleGlobal->VolatileLastVariableOffset = (UINTN) GetStartPointer (VolatileVariableStore) - (UINTN) VolatileVariableStore;\r
 \r
-  VolatileVariableStore->Signature                  = VARIABLE_STORE_SIGNATURE;\r
-  VolatileVariableStore->Size                       = FixedPcdGet32(PcdVariableStoreSize);\r
-  VolatileVariableStore->Format                     = VARIABLE_STORE_FORMATTED;\r
-  VolatileVariableStore->State                      = VARIABLE_STORE_HEALTHY;\r
-  VolatileVariableStore->Reserved                   = 0;\r
-  VolatileVariableStore->Reserved1                  = 0;\r
+  CopyGuid (&VolatileVariableStore->Signature, &gEfiVariableGuid);\r
+  VolatileVariableStore->Size        = PcdGet32 (PcdVariableStoreSize);\r
+  VolatileVariableStore->Format      = VARIABLE_STORE_FORMATTED;\r
+  VolatileVariableStore->State       = VARIABLE_STORE_HEALTHY;\r
+  VolatileVariableStore->Reserved    = 0;\r
+  VolatileVariableStore->Reserved1   = 0;\r
 \r
   //\r
-  // Get non volatile varaible store\r
+  // Init non-volatile variable store.\r
   //\r
-\r
-  TempVariableStoreHeader = (UINT64) PcdGet32 (PcdFlashNvStorageVariableBase);\r
-  VariableStoreBase = TempVariableStoreHeader + \\r
-                              (((EFI_FIRMWARE_VOLUME_HEADER *) (UINTN) (TempVariableStoreHeader)) -> HeaderLength);\r
-  VariableStoreLength = (UINT64) PcdGet32 (PcdFlashNvStorageVariableSize) - \\r
-                                (((EFI_FIRMWARE_VOLUME_HEADER *) (UINTN) (TempVariableStoreHeader)) -> HeaderLength);\r
-  //\r
-  // Mark the variable storage region of the FLASH as RUNTIME\r
-  //\r
-  BaseAddress = VariableStoreBase & (~EFI_PAGE_MASK);\r
-  Length      = VariableStoreLength + (VariableStoreBase - BaseAddress);\r
-  Length      = (Length + EFI_PAGE_SIZE - 1) & (~EFI_PAGE_MASK);\r
-\r
-  Status      = gDS->GetMemorySpaceDescriptor (BaseAddress, &GcdDescriptor);\r
+  Status = InitNonVolatileVariableStore ();\r
   if (EFI_ERROR (Status)) {\r
-    goto Done;\r
+    if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {\r
+      FreePool ((VOID *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase);\r
+    }\r
+    FreePool (mVariableModuleGlobal);\r
+    FreePool (VolatileVariableStore);\r
   }\r
 \r
-  Status = gDS->SetMemorySpaceAttributes (\r
-                  BaseAddress,\r
-                  Length,\r
-                  GcdDescriptor.Attributes | EFI_MEMORY_RUNTIME\r
-                  );\r
-  if (EFI_ERROR (Status)) {\r
-    goto Done;\r
-  }\r
-  //\r
-  // Get address of non volatile variable store base\r
-  //\r
-  mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;\r
+  return Status;\r
+}\r
+\r
+\r
+/**\r
+  Get the proper fvb handle and/or fvb protocol by the given Flash address.\r
+\r
+  @param[in] Address        The Flash address.\r
+  @param[out] FvbHandle     In output, if it is not NULL, it points to the proper FVB handle.\r
+  @param[out] FvbProtocol   In output, if it is not NULL, it points to the proper FVB protocol.\r
 \r
+**/\r
+EFI_STATUS\r
+GetFvbInfoByAddress (\r
+  IN  EFI_PHYSICAL_ADDRESS                Address,\r
+  OUT EFI_HANDLE                          *FvbHandle OPTIONAL,\r
+  OUT EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL  **FvbProtocol OPTIONAL\r
+  )\r
+{\r
+  EFI_STATUS                              Status;\r
+  EFI_HANDLE                              *HandleBuffer;\r
+  UINTN                                   HandleCount;\r
+  UINTN                                   Index;\r
+  EFI_PHYSICAL_ADDRESS                    FvbBaseAddress;\r
+  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL      *Fvb;\r
+  EFI_FIRMWARE_VOLUME_HEADER              *FwVolHeader;\r
+  EFI_FVB_ATTRIBUTES_2                    Attributes;\r
\r
   //\r
-  // Check Integrity\r
+  // Get all FVB handles.\r
   //\r
+  Status = GetFvbCountAndBuffer (&HandleCount, &HandleBuffer);\r
+  if (EFI_ERROR (Status)) {\r
+    return EFI_NOT_FOUND;\r
+  }\r
+\r
   //\r
-  // Find the Correct Instance of the FV Block Service.\r
+  // Get the FVB to access variable store.\r
   //\r
-  Instance  = 0;\r
-  CurrPtr   = (CHAR8 *) ((UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase);\r
-  while (EfiFvbGetPhysicalAddress (Instance, &FvVolHdr) == EFI_SUCCESS) {\r
-    FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *) ((UINTN) FvVolHdr);\r
-    if (CurrPtr >= (CHAR8 *) FwVolHeader && CurrPtr < (((CHAR8 *) FwVolHeader) + FwVolHeader->FvLength)) {\r
-      mVariableModuleGlobal->FvbInstance = Instance;\r
+  Fvb = NULL;\r
+  for (Index = 0; Index < HandleCount; Index += 1, Status = EFI_NOT_FOUND, Fvb = NULL) {\r
+    Status = GetFvbByHandle (HandleBuffer[Index], &Fvb);\r
+    if (EFI_ERROR (Status)) {\r
+      Status = EFI_NOT_FOUND;\r
       break;\r
     }\r
 \r
-    Instance++;\r
-  }\r
-\r
-  VariableStoreHeader = (VARIABLE_STORE_HEADER *) CurrPtr;\r
-  if (GetVariableStoreStatus (VariableStoreHeader) == EfiValid) {\r
-    if (~VariableStoreHeader->Size == 0) {\r
-      Status = UpdateVariableStore (\r
-                &mVariableModuleGlobal->VariableGlobal,\r
-                FALSE,\r
-                FALSE,\r
-                mVariableModuleGlobal->FvbInstance,\r
-                (UINTN) &VariableStoreHeader->Size,\r
-                sizeof (UINT32),\r
-                (UINT8 *) &VariableStoreLength\r
-                );\r
-      //\r
-      // As Variables are stored in NV storage, which are slow devices,such as flash.\r
-      // Variable operation may skip checking variable program result to improve performance,\r
-      // We can assume Variable program is OK through some check point.\r
-      // Variable Store Size Setting should be the first Variable write operation,\r
-      // We can assume all Read/Write is OK if we can set Variable store size successfully.\r
-      // If write fail, we will assert here\r
-      //\r
-      ASSERT(VariableStoreHeader->Size == VariableStoreLength);\r
-\r
-      if (EFI_ERROR (Status)) {\r
-        goto Done;\r
-      }\r
-    }\r
-\r
-    mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = (EFI_PHYSICAL_ADDRESS) ((UINTN) CurrPtr);\r
     //\r
-    // Parse non-volatile variable data and get last variable offset\r
+    // Ensure this FVB protocol supported Write operation.\r
     //\r
-    NextVariable  = GetStartPointer ((VARIABLE_STORE_HEADER *) CurrPtr);\r
-    Status        = EFI_SUCCESS;\r
-\r
-    while (IsValidVariableHeader (NextVariable)) {\r
-      NextVariable = GetNextVariablePtr (NextVariable);\r
+    Status = Fvb->GetAttributes (Fvb, &Attributes);\r
+    if (EFI_ERROR (Status) || ((Attributes & EFI_FVB2_WRITE_STATUS) == 0)) {\r
+      continue;     \r
     }\r
-\r
-    mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) CurrPtr;\r
-\r
+    \r
     //\r
-    // Check if the free area is really free.\r
+    // Compare the address and select the right one.\r
     //\r
-    for (Index = mVariableModuleGlobal->NonVolatileLastVariableOffset; Index < VariableStoreHeader->Size; Index++) {\r
-      Data = ((UINT8 *) (UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase)[Index];\r
-      if (Data != 0xff) {\r
-        //\r
-        // There must be something wrong in variable store, do reclaim operation.\r
-        //\r
-        Status = Reclaim (\r
-                  mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,\r
-                  &mVariableModuleGlobal->NonVolatileLastVariableOffset,\r
-                  FALSE,\r
-                  NULL\r
-                  );\r
-\r
-        if (EFI_ERROR (Status)) {\r
-          goto Done;\r
-        }\r
+    Status = Fvb->GetPhysicalAddress (Fvb, &FvbBaseAddress);\r
+    if (EFI_ERROR (Status)) {\r
+      continue;\r
+    }\r
 \r
-        break;\r
+    FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *) ((UINTN) FvbBaseAddress);\r
+    if ((Address >= FvbBaseAddress) && (Address < (FvbBaseAddress + FwVolHeader->FvLength))) {\r
+      if (FvbHandle != NULL) {\r
+        *FvbHandle  = HandleBuffer[Index];\r
       }\r
+      if (FvbProtocol != NULL) {\r
+        *FvbProtocol = Fvb;\r
+      }\r
+      Status = EFI_SUCCESS;\r
+      break;\r
     }\r
-\r
-    //\r
-    // Register the event handling function to reclaim variable for OS usage.\r
-    //\r
-    Status = EfiCreateEventReadyToBootEx (\r
-               TPL_NOTIFY, \r
-               ReclaimForOS, \r
-               NULL, \r
-               &ReadyToBootEvent\r
-               );\r
   }\r
+  FreePool (HandleBuffer);\r
 \r
-Done:\r
-  if (EFI_ERROR (Status)) {\r
-    FreePool (mVariableModuleGlobal);\r
-    FreePool (VolatileVariableStore);\r
+  if (Fvb == NULL) {\r
+    Status = EFI_NOT_FOUND;\r
   }\r
-\r
-  return Status;\r
-}\r
-\r
-/**\r
-  Notification function of EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE\r
-\r
-  This is a notification function registered on EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE event.\r
-  It convers pointer to new virtual address.\r
-\r
-  @param  Event        Event whose notification function is being invoked\r
-  @param  Context      Pointer to the notification function's context\r
-\r
-**/\r
-VOID\r
-EFIAPI\r
-VariableClassAddressChangeEvent (\r
-  IN EFI_EVENT        Event,\r
-  IN VOID             *Context\r
-  )\r
-{\r
-  EfiConvertPointer (\r
-    0x0,\r
-    (VOID **) &mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase\r
-    );\r
-  EfiConvertPointer (\r
-    0x0,\r
-    (VOID **) &mVariableModuleGlobal->VariableGlobal.VolatileVariableBase\r
-    );\r
-  EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal);\r
-}\r
-\r
-\r
-/**\r
-  Variable Driver main entry point. The Variable driver places the 4 EFI\r
-  runtime services in the EFI System Table and installs arch protocols \r
-  for variable read and write services being availible. It also registers\r
-  notification function for EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE event.\r
-\r
-  @param[in] ImageHandle    The firmware allocated handle for the EFI image.  \r
-  @param[in] SystemTable    A pointer to the EFI System Table.\r
   \r
-  @retval EFI_SUCCESS       Variable service successfully initialized.\r
-\r
-**/\r
-EFI_STATUS\r
-EFIAPI\r
-VariableServiceInitialize (\r
-  IN EFI_HANDLE         ImageHandle,\r
-  IN EFI_SYSTEM_TABLE   *SystemTable\r
-  )\r
-{\r
-  EFI_STATUS  Status;\r
-\r
-  Status = VariableCommonInitialize (ImageHandle, SystemTable);\r
-  ASSERT_EFI_ERROR (Status);\r
-\r
-  SystemTable->RuntimeServices->GetVariable         = RuntimeServiceGetVariable;\r
-  SystemTable->RuntimeServices->GetNextVariableName = RuntimeServiceGetNextVariableName;\r
-  SystemTable->RuntimeServices->SetVariable         = RuntimeServiceSetVariable;\r
-  SystemTable->RuntimeServices->QueryVariableInfo   = RuntimeServiceQueryVariableInfo;\r
-\r
-  //\r
-  // Now install the Variable Runtime Architectural Protocol on a new handle\r
-  //\r
-  Status = gBS->InstallMultipleProtocolInterfaces (\r
-                  &mHandle,\r
-                  &gEfiVariableArchProtocolGuid,        NULL,\r
-                  &gEfiVariableWriteArchProtocolGuid,   NULL,\r
-                  NULL\r
-                  );\r
-  ASSERT_EFI_ERROR (Status);\r
-\r
-  Status = gBS->CreateEvent (\r
-                  EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE,\r
-                  TPL_NOTIFY,\r
-                  VariableClassAddressChangeEvent,\r
-                  NULL,\r
-                  &mVirtualAddressChangeEvent\r
-                  );\r
-  ASSERT_EFI_ERROR (Status);\r
-\r
-  return EFI_SUCCESS;\r
+  return Status;  \r
 }\r
 \r