]> git.proxmox.com Git - mirror_edk2.git/blobdiff - MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
MdeModulePkg VariableDxe: Update it supports normal format variable storage
[mirror_edk2.git] / MdeModulePkg / Universal / Variable / RuntimeDxe / Variable.c
index 4f0ea3c4b703b6260a9b9be61bc25be3689dd1f9..77905a0a308086d3b7dc8acebc723dcaae159b4d 100644 (file)
 /** @file\r
+  The common variable operation routines shared by DXE_RUNTIME variable\r
+  module and DXE_SMM variable module.\r
 \r
-  Implement all four UEFI Runtime Variable services for the nonvolatile\r
-  and volatile storage space and install variable architecture protocol.\r
-  \r
-Copyright (c) 2006 - 2009, Intel Corporation                                                         \r
-All rights reserved. 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
+  Caution: This module requires additional review when modified.\r
+  This driver will have external input - variable data. They may be input in SMM mode.\r
+  This external input must be validated carefully to avoid security issue like\r
+  buffer overflow, integer overflow.\r
 \r
-THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
-WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+  VariableServiceGetNextVariableName () and VariableServiceQueryVariableInfo() are external API.\r
+  They need check input parameter.\r
+\r
+  VariableServiceGetVariable() and VariableServiceSetVariable() are external API\r
+  to receive datasize and data buffer. The size should be checked carefully.\r
+\r
+  VariableServiceSetVariable() should also check authenticate data to avoid buffer overflow,\r
+  integer overflow. It should also check attribute to avoid authentication bypass.\r
+\r
+Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.<BR>\r
+(C) Copyright 2015 Hewlett Packard Enterprise Development LP<BR>\r
+This program and the accompanying materials\r
+are licensed and made available under the terms and conditions of the BSD License\r
+which accompanies this distribution.  The full text of the license may be found at\r
+http://opensource.org/licenses/bsd-license.php\r
+\r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
 \r
 **/\r
 \r
 #include "Variable.h"\r
 \r
 VARIABLE_MODULE_GLOBAL  *mVariableModuleGlobal;\r
-EFI_EVENT   mVirtualAddressChangeEvent = NULL;\r
-EFI_HANDLE  mHandle = NULL;\r
+\r
 ///\r
-/// The size of a 3 character ISO639 language code.\r
+/// Define a memory cache that improves the search performance for a variable.\r
 ///\r
-#define ISO_639_2_ENTRY_SIZE    3\r
+VARIABLE_STORE_HEADER  *mNvVariableCache      = 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
+/// Memory cache of Fv Header.\r
 ///\r
-VARIABLE_CACHE_ENTRY mVariableCache[] = {\r
-  {\r
-    &gEfiGlobalVariableGuid,\r
-    L"Lang",\r
-    0x00000000,\r
-    0x00,\r
-    NULL\r
-  },\r
-  {\r
-    &gEfiGlobalVariableGuid,\r
-    L"PlatformLang",\r
-    0x00000000,\r
-    0x00,\r
-    NULL\r
-  }\r
-};\r
-\r
-VARIABLE_INFO_ENTRY *gVariableInfo      = NULL;\r
-EFI_EVENT           mFvbRegistration    = NULL;\r
-\r
-/**\r
-  Update the variable region with Variable information. These are the same \r
-  arguments as the EFI Variable services.\r
-\r
-  @param[in] VariableName       Name of variable\r
-\r
-  @param[in] VendorGuid         Guid of variable\r
-\r
-  @param[in] Data               Variable data\r
-\r
-  @param[in] DataSize           Size of data. 0 means delete\r
-\r
-  @param[in] Attributes              Attribues of the variable\r
-\r
-  @param[in] Variable           The variable information which is used to keep track of variable usage.\r
-\r
-  @retval EFI_SUCCESS           The update operation is success.\r
-\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
-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      VARIABLE_POINTER_TRACK *Variable\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
+EFI_FIRMWARE_VOLUME_HEADER *mNvFvHeaderCache  = NULL;\r
 \r
-  @param  Lock         A pointer to the lock to acquire\r
+///\r
+/// The memory entry used for variable statistics data.\r
+///\r
+VARIABLE_INFO_ENTRY    *gVariableInfo         = NULL;\r
 \r
-**/\r
-VOID\r
-AcquireLockOnlyAtBootTime (\r
-  IN EFI_LOCK  *Lock\r
-  )\r
-{\r
-  if (!EfiAtRuntime ()) {\r
-    EfiAcquireLock (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
-  Releases lock only at boot time. Simply returns at runtime.\r
+///\r
+/// It indicates the var check request source.\r
+/// In the implementation, DXE is regarded as untrusted, and SMM is trusted.\r
+///\r
+VAR_CHECK_REQUEST_SOURCE mRequestSource       = VarCheckFromUntrusted;\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
+// It will record the current boot error flag before EndOfDxe.\r
+//\r
+VAR_ERROR_FLAG         mCurrentBootVarErrFlag = VAR_ERROR_FLAG_NO_ERROR;\r
 \r
-  @param  Lock         A pointer to the lock to release\r
+VARIABLE_ENTRY_PROPERTY mVariableEntryProperty[] = {\r
+  {\r
+    &gEdkiiVarErrorFlagGuid,\r
+    VAR_ERROR_FLAG_NAME,\r
+    {\r
+      VAR_CHECK_VARIABLE_PROPERTY_REVISION,\r
+      VAR_CHECK_VARIABLE_PROPERTY_READ_ONLY,\r
+      VARIABLE_ATTRIBUTE_NV_BS_RT,\r
+      sizeof (VAR_ERROR_FLAG),\r
+      sizeof (VAR_ERROR_FLAG)\r
+    }\r
+  },\r
+};\r
 \r
-**/\r
-VOID\r
-ReleaseLockOnlyAtBootTime (\r
-  IN EFI_LOCK  *Lock\r
-  )\r
-{\r
-  if (!EfiAtRuntime ()) {\r
-    EfiReleaseLock (Lock);\r
-  }\r
-}\r
+AUTH_VAR_LIB_CONTEXT_IN mAuthContextIn = {\r
+  AUTH_VAR_LIB_CONTEXT_IN_STRUCT_VERSION,\r
+  //\r
+  // StructSize, TO BE FILLED\r
+  //\r
+  0,\r
+  //\r
+  // MaxAuthVariableSize, TO BE FILLED\r
+  //\r
+  0,\r
+  VariableExLibFindVariable,\r
+  VariableExLibFindNextVariable,\r
+  VariableExLibUpdateVariable,\r
+  VariableExLibGetScratchBuffer,\r
+  VariableExLibCheckRemainingSpaceForConsistency,\r
+  VariableExLibAtRuntime,\r
+};\r
 \r
+AUTH_VAR_LIB_CONTEXT_OUT mAuthContextOut;\r
 \r
 /**\r
-  Routine used to track statistical information about variable usage. \r
+  Routine used to track statistical information about variable usage.\r
   The data is stored in the EFI system table so it can be accessed later.\r
-  VariableInfo.efi can dump out the table. Only Boot Services variable \r
+  VariableInfo.efi can dump out the table. Only Boot Services variable\r
   accesses are tracked by this code. The PcdVariableCollectStatistics\r
-  build flag controls if this feature is enabled. \r
+  build flag controls if this feature is enabled.\r
 \r
-  A read that hits in the cache will have Read and Cache true for \r
+  A read that hits in the cache will have Read and Cache true for\r
   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
@@ -162,29 +132,27 @@ 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 (StrSize (VariableName));\r
+      gVariableInfo->Name = AllocateZeroPool (StrSize (VariableName));\r
       ASSERT (gVariableInfo->Name != NULL);\r
-      StrCpy (gVariableInfo->Name, VariableName);\r
+      StrCpyS (gVariableInfo->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName);\r
       gVariableInfo->Volatile = Volatile;\r
-\r
-      gBS->InstallConfigurationTable (&gEfiVariableGuid, gVariableInfo);\r
     }\r
 \r
-    \r
+\r
     for (Entry = gVariableInfo; Entry != NULL; Entry = Entry->Next) {\r
       if (CompareGuid (VendorGuid, &Entry->VendorGuid)) {\r
         if (StrCmp (VariableName, Entry->Name) == 0) {\r
@@ -208,15 +176,15 @@ 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 (StrSize (VariableName));\r
+        Entry->Next->Name = AllocateZeroPool (StrSize (VariableName));\r
         ASSERT (Entry->Next->Name != NULL);\r
-        StrCpy (Entry->Next->Name, VariableName);\r
+        StrCpyS (Entry->Next->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName);\r
         Entry->Next->Volatile = Volatile;\r
       }\r
 \r
@@ -229,18 +197,24 @@ UpdateVariableInfo (
 \r
   This code checks if variable header is valid or not.\r
 \r
-  @param Variable        Pointer to the Variable Header.\r
+  @param Variable           Pointer to the Variable Header.\r
+  @param VariableStoreEnd   Pointer to the Variable Store End.\r
 \r
-  @retval TRUE           Variable header is valid.\r
-  @retval FALSE          Variable header is not valid.\r
+  @retval TRUE              Variable header is valid.\r
+  @retval FALSE             Variable header is not valid.\r
 \r
 **/\r
 BOOLEAN\r
 IsValidVariableHeader (\r
-  IN  VARIABLE_HEADER   *Variable\r
+  IN  VARIABLE_HEADER       *Variable,\r
+  IN  VARIABLE_HEADER       *VariableStoreEnd\r
   )\r
 {\r
-  if (Variable == NULL || Variable->StartId != VARIABLE_DATA) {\r
+  if ((Variable == NULL) || (Variable >= VariableStoreEnd) || (Variable->StartId != VARIABLE_DATA)) {\r
+    //\r
+    // Variable is NULL or has reached the end of variable store,\r
+    // or the StartId is not correct.\r
+    //\r
     return FALSE;\r
   }\r
 \r
@@ -253,18 +227,18 @@ 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 Fvb                     Pointer to the writable FVB protocol\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
@@ -296,16 +270,19 @@ UpdateVariableStore (
   DataPtr     = DataPtrIndex;\r
 \r
   //\r
-  // Check if the Data is Volatile\r
+  // Check if the Data is Volatile.\r
   //\r
   if (!Volatile) {\r
+    if (Fvb == NULL) {\r
+      return EFI_INVALID_PARAMETER;\r
+    }\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
@@ -317,7 +294,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
@@ -327,16 +304,16 @@ UpdateVariableStore (
     if ((DataPtr + DataSize) >= ((UINTN) ((UINT8 *) VolatileBase + VolatileBase->Size))) {\r
       return EFI_INVALID_PARAMETER;\r
     }\r
-    \r
+\r
     //\r
     // If Volatile Variable just do a simple mem copy.\r
-    //    \r
+    //\r
     CopyMem ((UINT8 *)(UINTN)DataPtr, Buffer, DataSize);\r
     return EFI_SUCCESS;\r
   }\r
-  \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
@@ -348,7 +325,7 @@ UpdateVariableStore (
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
-  for (PtrBlockMapEntry = FwVolHeader->BlockMap; PtrBlockMapEntry->NumBlocks != 0; PtrBlockMapEntry++) {\r
+  for (PtrBlockMapEntry = mNvFvHeaderCache->BlockMap; PtrBlockMapEntry->NumBlocks != 0; PtrBlockMapEntry++) {\r
     for (BlockIndex2 = 0; BlockIndex2 < PtrBlockMapEntry->NumBlocks; BlockIndex2++) {\r
       //\r
       // Check to see if the Variable Writes are spanning through multiple\r
@@ -398,9 +375,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
@@ -408,7 +385,8 @@ GetVariableStoreStatus (
   IN VARIABLE_STORE_HEADER *VarStoreHeader\r
   )\r
 {\r
-  if (CompareGuid (&VarStoreHeader->Signature, &gEfiVariableGuid) &&\r
+  if ((CompareGuid (&VarStoreHeader->Signature, &gEfiAuthenticatedVariableGuid) ||\r
+       CompareGuid (&VarStoreHeader->Signature, &gEfiVariableGuid)) &&\r
       VarStoreHeader->Format == VARIABLE_STORE_FORMATTED &&\r
       VarStoreHeader->State == VARIABLE_STORE_HEALTHY\r
       ) {\r
@@ -429,14 +407,35 @@ GetVariableStoreStatus (
   }\r
 }\r
 \r
+/**\r
+  This code gets the size of variable header.\r
+\r
+  @return Size of variable header in bytes in type UINTN.\r
+\r
+**/\r
+UINTN\r
+GetVariableHeaderSize (\r
+  VOID\r
+  )\r
+{\r
+  UINTN Value;\r
+\r
+  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {\r
+    Value = sizeof (AUTHENTICATED_VARIABLE_HEADER);\r
+  } else {\r
+    Value = sizeof (VARIABLE_HEADER);\r
+  }\r
+\r
+  return Value;\r
+}\r
 \r
 /**\r
 \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
@@ -444,22 +443,58 @@ NameSizeOfVariable (
   IN  VARIABLE_HEADER   *Variable\r
   )\r
 {\r
-  if (Variable->State    == (UINT8) (-1) ||\r
-      Variable->DataSize == (UINT32) (-1) ||\r
-      Variable->NameSize == (UINT32) (-1) ||\r
-      Variable->Attributes == (UINT32) (-1)) {\r
-    return 0;\r
+  AUTHENTICATED_VARIABLE_HEADER *AuthVariable;\r
+\r
+  AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;\r
+  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {\r
+    if (AuthVariable->State == (UINT8) (-1) ||\r
+       AuthVariable->DataSize == (UINT32) (-1) ||\r
+       AuthVariable->NameSize == (UINT32) (-1) ||\r
+       AuthVariable->Attributes == (UINT32) (-1)) {\r
+      return 0;\r
+    }\r
+    return (UINTN) AuthVariable->NameSize;\r
+  } else {\r
+    if (Variable->State == (UINT8) (-1) ||\r
+        Variable->DataSize == (UINT32) (-1) ||\r
+        Variable->NameSize == (UINT32) (-1) ||\r
+        Variable->Attributes == (UINT32) (-1)) {\r
+      return 0;\r
+    }\r
+    return (UINTN) Variable->NameSize;\r
+  }\r
+}\r
+\r
+/**\r
+  This code sets the size of name of variable.\r
+\r
+  @param[in] Variable   Pointer to the Variable Header.\r
+  @param[in] NameSize   Name size to set.\r
+\r
+**/\r
+VOID\r
+SetNameSizeOfVariable (\r
+  IN VARIABLE_HEADER    *Variable,\r
+  IN UINTN              NameSize\r
+  )\r
+{\r
+  AUTHENTICATED_VARIABLE_HEADER *AuthVariable;\r
+\r
+  AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;\r
+  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {\r
+    AuthVariable->NameSize = (UINT32) NameSize;\r
+  } else {\r
+    Variable->NameSize = (UINT32) NameSize;\r
   }\r
-  return (UINTN) Variable->NameSize;\r
 }\r
 \r
 /**\r
 \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
@@ -467,22 +502,58 @@ DataSizeOfVariable (
   IN  VARIABLE_HEADER   *Variable\r
   )\r
 {\r
-  if (Variable->State    == (UINT8)  (-1) ||\r
-      Variable->DataSize == (UINT32) (-1) ||\r
-      Variable->NameSize == (UINT32) (-1) ||\r
-      Variable->Attributes == (UINT32) (-1)) {\r
-    return 0;\r
+  AUTHENTICATED_VARIABLE_HEADER *AuthVariable;\r
+\r
+  AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;\r
+  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {\r
+    if (AuthVariable->State == (UINT8) (-1) ||\r
+       AuthVariable->DataSize == (UINT32) (-1) ||\r
+       AuthVariable->NameSize == (UINT32) (-1) ||\r
+       AuthVariable->Attributes == (UINT32) (-1)) {\r
+      return 0;\r
+    }\r
+    return (UINTN) AuthVariable->DataSize;\r
+  } else {\r
+    if (Variable->State == (UINT8) (-1) ||\r
+        Variable->DataSize == (UINT32) (-1) ||\r
+        Variable->NameSize == (UINT32) (-1) ||\r
+        Variable->Attributes == (UINT32) (-1)) {\r
+      return 0;\r
+    }\r
+    return (UINTN) Variable->DataSize;\r
+  }\r
+}\r
+\r
+/**\r
+  This code sets the size of variable data.\r
+\r
+  @param[in] Variable   Pointer to the Variable Header.\r
+  @param[in] DataSize   Data size to set.\r
+\r
+**/\r
+VOID\r
+SetDataSizeOfVariable (\r
+  IN VARIABLE_HEADER    *Variable,\r
+  IN UINTN              DataSize\r
+  )\r
+{\r
+  AUTHENTICATED_VARIABLE_HEADER *AuthVariable;\r
+\r
+  AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;\r
+  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {\r
+    AuthVariable->DataSize = (UINT32) DataSize;\r
+  } else {\r
+    Variable->DataSize = (UINT32) DataSize;\r
   }\r
-  return (UINTN) Variable->DataSize;\r
 }\r
 \r
 /**\r
 \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
@@ -490,17 +561,39 @@ GetVariableNamePtr (
   IN  VARIABLE_HEADER   *Variable\r
   )\r
 {\r
+  return (CHAR16 *) ((UINTN) Variable + GetVariableHeaderSize ());\r
+}\r
+\r
+/**\r
+  This code gets the pointer to the variable guid.\r
+\r
+  @param Variable   Pointer to the Variable Header.\r
+\r
+  @return A EFI_GUID* pointer to Vendor Guid.\r
+\r
+**/\r
+EFI_GUID *\r
+GetVendorGuidPtr (\r
+  IN VARIABLE_HEADER    *Variable\r
+  )\r
+{\r
+  AUTHENTICATED_VARIABLE_HEADER *AuthVariable;\r
 \r
-  return (CHAR16 *) (Variable + 1);\r
+  AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;\r
+  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {\r
+    return &AuthVariable->VendorGuid;\r
+  } else {\r
+    return &Variable->VendorGuid;\r
+  }\r
 }\r
 \r
 /**\r
 \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
@@ -509,9 +602,9 @@ GetVariableDataPtr (
   )\r
 {\r
   UINTN Value;\r
-  \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
@@ -520,14 +613,38 @@ GetVariableDataPtr (
   return (UINT8 *) Value;\r
 }\r
 \r
+/**\r
+  This code gets the variable data offset related to variable header.\r
+\r
+  @param Variable        Pointer to the Variable Header.\r
+\r
+  @return Variable Data offset.\r
+\r
+**/\r
+UINTN\r
+GetVariableDataOffset (\r
+  IN  VARIABLE_HEADER   *Variable\r
+  )\r
+{\r
+  UINTN Value;\r
+\r
+  //\r
+  // Be careful about pad size for alignment\r
+  //\r
+  Value = GetVariableHeaderSize ();\r
+  Value += NameSizeOfVariable (Variable);\r
+  Value += GET_PAD_SIZE (NameSizeOfVariable (Variable));\r
+\r
+  return Value;\r
+}\r
 \r
 /**\r
 \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
@@ -537,16 +654,12 @@ GetNextVariablePtr (
 {\r
   UINTN Value;\r
 \r
-  if (!IsValidVariableHeader (Variable)) {\r
-    return NULL;\r
-  }\r
-\r
   Value =  (UINTN) GetVariableDataPtr (Variable);\r
   Value += DataSizeOfVariable (Variable);\r
   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
@@ -557,7 +670,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
@@ -566,7 +679,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
@@ -578,9 +691,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
@@ -594,170 +707,386 @@ GetEndPointer (
   return (VARIABLE_HEADER *) HEADER_ALIGN ((UINTN) VarStoreHeader + VarStoreHeader->Size);\r
 }\r
 \r
-\r
 /**\r
+  Record variable error flag.\r
 \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
-\r
-  @return EFI_OUT_OF_RESOURCES\r
-  @return EFI_SUCCESS\r
-  @return Others\r
+  @param[in] Flag               Variable error flag to record.\r
+  @param[in] VariableName       Name of variable.\r
+  @param[in] VendorGuid         Guid of variable.\r
+  @param[in] Attributes         Attributes of the variable.\r
+  @param[in] VariableSize       Size of the variable.\r
 \r
 **/\r
-EFI_STATUS\r
-Reclaim (\r
-  IN  EFI_PHYSICAL_ADDRESS  VariableBase,\r
-  OUT UINTN                 *LastVariableOffset,\r
-  IN  BOOLEAN               IsVolatile,\r
-  IN  VARIABLE_HEADER       *UpdatingVariable\r
+VOID\r
+RecordVarErrorFlag (\r
+  IN VAR_ERROR_FLAG         Flag,\r
+  IN CHAR16                 *VariableName,\r
+  IN EFI_GUID               *VendorGuid,\r
+  IN UINT32                 Attributes,\r
+  IN UINTN                  VariableSize\r
   )\r
 {\r
-  VARIABLE_HEADER       *Variable;\r
-  VARIABLE_HEADER       *AddedVariable;\r
-  VARIABLE_HEADER       *NextVariable;\r
-  VARIABLE_HEADER       *NextAddedVariable;\r
-  VARIABLE_STORE_HEADER *VariableStoreHeader;\r
-  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
+  EFI_STATUS                Status;\r
+  VARIABLE_POINTER_TRACK    Variable;\r
+  VAR_ERROR_FLAG            *VarErrFlag;\r
+  VAR_ERROR_FLAG            TempFlag;\r
+\r
+  DEBUG_CODE (\r
+    DEBUG ((EFI_D_ERROR, "RecordVarErrorFlag (0x%02x) %s:%g - 0x%08x - 0x%x\n", Flag, VariableName, VendorGuid, Attributes, VariableSize));\r
+    if (Flag == VAR_ERROR_FLAG_SYSTEM_ERROR) {\r
+      if (AtRuntime ()) {\r
+        DEBUG ((EFI_D_ERROR, "CommonRuntimeVariableSpace = 0x%x - CommonVariableTotalSize = 0x%x\n", mVariableModuleGlobal->CommonRuntimeVariableSpace, mVariableModuleGlobal->CommonVariableTotalSize));\r
+      } else {\r
+        DEBUG ((EFI_D_ERROR, "CommonVariableSpace = 0x%x - CommonVariableTotalSize = 0x%x\n", mVariableModuleGlobal->CommonVariableSpace, mVariableModuleGlobal->CommonVariableTotalSize));\r
+      }\r
+    } else {\r
+      DEBUG ((EFI_D_ERROR, "CommonMaxUserVariableSpace = 0x%x - CommonUserVariableTotalSize = 0x%x\n", mVariableModuleGlobal->CommonMaxUserVariableSpace, mVariableModuleGlobal->CommonUserVariableTotalSize));\r
+    }\r
+  );\r
 \r
-  VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) VariableBase);\r
-  //\r
-  // recaluate the total size of Common/HwErr type variables in non-volatile area.\r
-  //\r
-  if (!IsVolatile) {\r
-    mVariableModuleGlobal->CommonVariableTotalSize = 0;\r
-    mVariableModuleGlobal->HwErrVariableTotalSize  = 0;\r
+  if (!mEndOfDxe) {\r
+    //\r
+    // Before EndOfDxe, just record the current boot variable error flag to local variable,\r
+    // and leave the variable error flag in NV flash as the last boot variable error flag.\r
+    // After EndOfDxe in InitializeVarErrorFlag (), the variable error flag in NV flash\r
+    // will be initialized to this local current boot variable error flag.\r
+    //\r
+    mCurrentBootVarErrFlag &= Flag;\r
+    return;\r
   }\r
 \r
   //\r
-  // Start Pointers for the variable.\r
+  // Record error flag (it should have be initialized).\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 || \r
-        Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)\r
-       ) {\r
-      VariableSize = (UINTN) NextVariable - (UINTN) Variable;\r
-      MaximumBufferSize += VariableSize;\r
+  Status = FindVariable (\r
+             VAR_ERROR_FLAG_NAME,\r
+             &gEdkiiVarErrorFlagGuid,\r
+             &Variable,\r
+             &mVariableModuleGlobal->VariableGlobal,\r
+             FALSE\r
+             );\r
+  if (!EFI_ERROR (Status)) {\r
+    VarErrFlag = (VAR_ERROR_FLAG *) GetVariableDataPtr (Variable.CurrPtr);\r
+    TempFlag = *VarErrFlag;\r
+    TempFlag &= Flag;\r
+    if (TempFlag == *VarErrFlag) {\r
+      return;\r
+    }\r
+    Status = UpdateVariableStore (\r
+               &mVariableModuleGlobal->VariableGlobal,\r
+               FALSE,\r
+               FALSE,\r
+               mVariableModuleGlobal->FvbInstance,\r
+               (UINTN) VarErrFlag - (UINTN) mNvVariableCache + (UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,\r
+               sizeof (TempFlag),\r
+               &TempFlag\r
+               );\r
+    if (!EFI_ERROR (Status)) {\r
+      //\r
+      // Update the data in NV cache.\r
+      //\r
+      *VarErrFlag = TempFlag;\r
     }\r
-\r
-    Variable = NextVariable;\r
   }\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
+/**\r
+  Initialize variable error flag.\r
 \r
-  SetMem (ValidBuffer, MaximumBufferSize, 0xff);\r
+  Before EndOfDxe, the variable indicates the last boot variable error flag,\r
+  then it means the last boot variable error flag must be got before EndOfDxe.\r
+  After EndOfDxe, the variable indicates the current boot variable error flag,\r
+  then it means the current boot variable error flag must be got after EndOfDxe.\r
 \r
-  //\r
-  // Copy variable store header\r
-  //\r
-  CopyMem (ValidBuffer, VariableStoreHeader, sizeof (VARIABLE_STORE_HEADER));\r
-  CurrPtr = (UINT8 *) GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer);\r
+**/\r
+VOID\r
+InitializeVarErrorFlag (\r
+  VOID\r
+  )\r
+{\r
+  EFI_STATUS                Status;\r
+  VARIABLE_POINTER_TRACK    Variable;\r
+  VAR_ERROR_FLAG            Flag;\r
+  VAR_ERROR_FLAG            VarErrFlag;\r
 \r
-  //\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
+  if (!mEndOfDxe) {\r
+    return;\r
+  }\r
 \r
-        VariableNameSize         = NameSizeOfVariable(Variable);\r
-        UpdatingVariableNameSize = NameSizeOfVariable(UpdatingVariable);\r
+  Flag = mCurrentBootVarErrFlag;\r
+  DEBUG ((EFI_D_INFO, "Initialize variable error flag (%02x)\n", Flag));\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
-      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
-        mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize;\r
-      } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {\r
-        mVariableModuleGlobal->CommonVariableTotalSize += VariableSize;\r
-      }\r
+  Status = FindVariable (\r
+             VAR_ERROR_FLAG_NAME,\r
+             &gEdkiiVarErrorFlagGuid,\r
+             &Variable,\r
+             &mVariableModuleGlobal->VariableGlobal,\r
+             FALSE\r
+             );\r
+  if (!EFI_ERROR (Status)) {\r
+    VarErrFlag = *((VAR_ERROR_FLAG *) GetVariableDataPtr (Variable.CurrPtr));\r
+    if (VarErrFlag == Flag) {\r
+      return;\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
-    if ((!IsVolatile) && ((UpdatingVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {\r
-        mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize;\r
-    } else if ((!IsVolatile) && ((UpdatingVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {\r
-        mVariableModuleGlobal->CommonVariableTotalSize += VariableSize;\r
-    }\r
-  }\r
+  UpdateVariable (\r
+    VAR_ERROR_FLAG_NAME,\r
+    &gEdkiiVarErrorFlagGuid,\r
+    &Flag,\r
+    sizeof (Flag),\r
+    VARIABLE_ATTRIBUTE_NV_BS_RT,\r
+    0,\r
+    0,\r
+    &Variable,\r
+    NULL\r
+    );\r
+}\r
 \r
-  //\r
-  // Reinstall all in delete transition variables\r
-  // \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
+/**\r
+  Is user variable?\r
+\r
+  @param[in] Variable   Pointer to variable header.\r
+\r
+  @retval TRUE          User variable.\r
+  @retval FALSE         System variable.\r
+\r
+**/\r
+BOOLEAN\r
+IsUserVariable (\r
+  IN VARIABLE_HEADER    *Variable\r
+  )\r
+{\r
+  VAR_CHECK_VARIABLE_PROPERTY   Property;\r
+\r
+  //\r
+  // Only after End Of Dxe, the variables belong to system variable are fixed.\r
+  // If PcdMaxUserNvStorageVariableSize is 0, it means user variable share the same NV storage with system variable,\r
+  // then no need to check if the variable is user variable or not specially.\r
+  //\r
+  if (mEndOfDxe && (mVariableModuleGlobal->CommonMaxUserVariableSpace != mVariableModuleGlobal->CommonVariableSpace)) {\r
+    if (VarCheckLibVariablePropertyGet (GetVariableNamePtr (Variable), GetVendorGuidPtr (Variable), &Property) == EFI_NOT_FOUND) {\r
+      return TRUE;\r
+    }\r
+  }\r
+  return FALSE;\r
+}\r
+\r
+/**\r
+  Calculate common user variable total size.\r
+\r
+**/\r
+VOID\r
+CalculateCommonUserVariableTotalSize (\r
+  VOID\r
+  )\r
+{\r
+  VARIABLE_HEADER               *Variable;\r
+  VARIABLE_HEADER               *NextVariable;\r
+  UINTN                         VariableSize;\r
+  VAR_CHECK_VARIABLE_PROPERTY   Property;\r
+\r
+  //\r
+  // Only after End Of Dxe, the variables belong to system variable are fixed.\r
+  // If PcdMaxUserNvStorageVariableSize is 0, it means user variable share the same NV storage with system variable,\r
+  // then no need to calculate the common user variable total size specially.\r
+  //\r
+  if (mEndOfDxe && (mVariableModuleGlobal->CommonMaxUserVariableSpace != mVariableModuleGlobal->CommonVariableSpace)) {\r
+    Variable = GetStartPointer (mNvVariableCache);\r
+    while (IsValidVariableHeader (Variable, GetEndPointer (mNvVariableCache))) {\r
+      NextVariable = GetNextVariablePtr (Variable);\r
+      VariableSize = (UINTN) NextVariable - (UINTN) Variable;\r
+      if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+        if (VarCheckLibVariablePropertyGet (GetVariableNamePtr (Variable), GetVendorGuidPtr (Variable), &Property) == EFI_NOT_FOUND) {\r
+          //\r
+          // No property, it is user variable.\r
+          //\r
+          mVariableModuleGlobal->CommonUserVariableTotalSize += VariableSize;\r
+        }\r
+      }\r
+\r
+      Variable = NextVariable;\r
+    }\r
+  }\r
+}\r
+\r
+/**\r
+  Initialize variable quota.\r
+\r
+**/\r
+VOID\r
+InitializeVariableQuota (\r
+  VOID\r
+  )\r
+{\r
+  if (!mEndOfDxe) {\r
+    return;\r
+  }\r
+\r
+  InitializeVarErrorFlag ();\r
+  CalculateCommonUserVariableTotalSize ();\r
+}\r
+\r
+/**\r
+\r
+  Variable store garbage collection and reclaim operation.\r
+\r
+  @param[in]      VariableBase            Base address of variable store.\r
+  @param[out]     LastVariableOffset      Offset of last variable.\r
+  @param[in]      IsVolatile              The variable store is volatile or not;\r
+                                          if it is non-volatile, need FTW.\r
+  @param[in, out] UpdatingPtrTrack        Pointer to updating variable pointer track structure.\r
+  @param[in]      NewVariable             Pointer to new variable.\r
+  @param[in]      NewVariableSize         New variable size.\r
+\r
+  @return EFI_SUCCESS                  Reclaim operation has finished successfully.\r
+  @return EFI_OUT_OF_RESOURCES         No enough memory resources or variable space.\r
+  @return Others                       Unexpect error happened during reclaim operation.\r
+\r
+**/\r
+EFI_STATUS\r
+Reclaim (\r
+  IN     EFI_PHYSICAL_ADDRESS         VariableBase,\r
+  OUT    UINTN                        *LastVariableOffset,\r
+  IN     BOOLEAN                      IsVolatile,\r
+  IN OUT VARIABLE_POINTER_TRACK       *UpdatingPtrTrack,\r
+  IN     VARIABLE_HEADER              *NewVariable,\r
+  IN     UINTN                        NewVariableSize\r
+  )\r
+{\r
+  VARIABLE_HEADER       *Variable;\r
+  VARIABLE_HEADER       *AddedVariable;\r
+  VARIABLE_HEADER       *NextVariable;\r
+  VARIABLE_HEADER       *NextAddedVariable;\r
+  VARIABLE_STORE_HEADER *VariableStoreHeader;\r
+  UINT8                 *ValidBuffer;\r
+  UINTN                 MaximumBufferSize;\r
+  UINTN                 VariableSize;\r
+  UINTN                 NameSize;\r
+  UINT8                 *CurrPtr;\r
+  VOID                  *Point0;\r
+  VOID                  *Point1;\r
+  BOOLEAN               FoundAdded;\r
+  EFI_STATUS            Status;\r
+  UINTN                 CommonVariableTotalSize;\r
+  UINTN                 CommonUserVariableTotalSize;\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
+  CommonVariableTotalSize = 0;\r
+  CommonUserVariableTotalSize = 0;\r
+  HwErrVariableTotalSize  = 0;\r
+\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, GetEndPointer (VariableStoreHeader))) {\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
+    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
+  } 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
+  //\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
+  //\r
+  Variable = GetStartPointer (VariableStoreHeader);\r
+  while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {\r
+    NextVariable = GetNextVariablePtr (Variable);\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
+        if (IsUserVariable (Variable)) {\r
+          CommonUserVariableTotalSize += VariableSize;\r
+        }\r
+      }\r
+    }\r
+    Variable = NextVariable;\r
+  }\r
+\r
+  //\r
+  // Reinstall all in delete transition variables.\r
+  //\r
+  Variable = GetStartPointer (VariableStoreHeader);\r
+  while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {\r
+    NextVariable = GetNextVariablePtr (Variable);\r
+    if (Variable != UpdatingVariable && Variable != UpdatingInDeletedTransition && Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
+\r
+      //\r
+      // Buffer has cached all ADDED variable.\r
+      // Per IN_DELETED variable, we have to guarantee that\r
+      // no ADDED one in previous buffer.\r
+      //\r
 \r
-      //\r
-      // Buffer has cached all ADDED variable. \r
-      // Per IN_DELETED variable, we have to guarantee that\r
-      // no ADDED one in previous buffer. \r
-      // \r
-     \r
       FoundAdded = FALSE;\r
       AddedVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer);\r
-      while (IsValidVariableHeader (AddedVariable)) {\r
+      while (IsValidVariableHeader (AddedVariable, GetEndPointer ((VARIABLE_STORE_HEADER *) ValidBuffer))) {\r
         NextAddedVariable = GetNextVariablePtr (AddedVariable);\r
         NameSize = NameSizeOfVariable (AddedVariable);\r
-        if (CompareGuid (&AddedVariable->VendorGuid, &Variable->VendorGuid) &&\r
+        if (CompareGuid (GetVendorGuidPtr (AddedVariable), GetVendorGuidPtr (Variable)) &&\r
             NameSize == NameSizeOfVariable (Variable)\r
            ) {\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
@@ -766,16 +1095,19 @@ 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
-          mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize;\r
+          HwErrVariableTotalSize += VariableSize;\r
         } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {\r
-          mVariableModuleGlobal->CommonVariableTotalSize += VariableSize;\r
+          CommonVariableTotalSize += VariableSize;\r
+          if (IsUserVariable (Variable)) {\r
+            CommonUserVariableTotalSize += VariableSize;\r
+          }\r
         }\r
       }\r
     }\r
@@ -783,175 +1115,196 @@ Reclaim (
     Variable = NextVariable;\r
   }\r
 \r
+  //\r
+  // Install the new variable if it is not NULL.\r
+  //\r
+  if (NewVariable != NULL) {\r
+    if (((UINTN) CurrPtr - (UINTN) 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
+        if (IsUserVariable (NewVariable)) {\r
+          CommonUserVariableTotalSize += NewVariableSize;\r
+        }\r
+      }\r
+      if ((HwErrVariableTotalSize > PcdGet32 (PcdHwErrStorageSize)) ||\r
+          (CommonVariableTotalSize > mVariableModuleGlobal->CommonVariableSpace) ||\r
+          (CommonUserVariableTotalSize > mVariableModuleGlobal->CommonMaxUserVariableSpace)) {\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 - (UINTN) ValidBuffer);\r
+    *LastVariableOffset = (UINTN) CurrPtr - (UINTN) 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
-  }\r
-  if (!EFI_ERROR (Status)) {\r
-    *LastVariableOffset = (UINTN) (CurrPtr - (UINT8 *) ValidBuffer);\r
-  } else {\r
-    *LastVariableOffset = 0;\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
-    //\r
-    // Don't use the cache at runtime\r
-    // \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
-          //\r
-          // Delete Case\r
-          //\r
-          if (Entry->DataSize != 0) {\r
-            FreePool (Entry->Data);\r
+    if (!EFI_ERROR (Status)) {\r
+      *LastVariableOffset = (UINTN) CurrPtr - (UINTN) ValidBuffer;\r
+      mVariableModuleGlobal->HwErrVariableTotalSize = HwErrVariableTotalSize;\r
+      mVariableModuleGlobal->CommonVariableTotalSize = CommonVariableTotalSize;\r
+      mVariableModuleGlobal->CommonUserVariableTotalSize = CommonUserVariableTotalSize;\r
+    } else {\r
+      mVariableModuleGlobal->HwErrVariableTotalSize = 0;\r
+      mVariableModuleGlobal->CommonVariableTotalSize = 0;\r
+      mVariableModuleGlobal->CommonUserVariableTotalSize = 0;\r
+      Variable = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableBase);\r
+      while (IsValidVariableHeader (Variable, GetEndPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableBase))) {\r
+        NextVariable = GetNextVariablePtr (Variable);\r
+        VariableSize = (UINTN) NextVariable - (UINTN) Variable;\r
+        if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+          mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize;\r
+        } else if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+          mVariableModuleGlobal->CommonVariableTotalSize += VariableSize;\r
+          if (IsUserVariable (Variable)) {\r
+            mVariableModuleGlobal->CommonUserVariableTotalSize += VariableSize;\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
-          ASSERT (Entry->Data != NULL);\r
-\r
-          Entry->DataSize = DataSize;\r
-          CopyMem (Entry->Data, Data, DataSize);\r
         }\r
+\r
+        Variable = NextVariable;\r
       }\r
+      *LastVariableOffset = (UINTN) Variable - (UINTN) VariableBase;\r
     }\r
   }\r
-}\r
-\r
 \r
-/**\r
-  Search the cache to check if the variable is in it.\r
+Done:\r
+  if (IsVolatile) {\r
+    FreePool (ValidBuffer);\r
+  } else {\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
-  This function searches the variable cache. If the variable to find exists, return its data\r
-  and attributes.\r
+  return Status;\r
+}\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
+/**\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[in]       VariableName        Name of the variable to be found\r
+  @param[in]       VendorGuid          Vendor GUID to be found.\r
+  @param[in]       IgnoreRtCheck       Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute\r
+                                       check at runtime when searching variable.\r
+  @param[in, out]  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
+      ; IsValidVariableHeader (PtrTrack->CurrPtr, PtrTrack->EndPtr)\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, GetVendorGuidPtr (PtrTrack->CurrPtr))) {\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  VendorGuid                  Vendor GUID to be found.\r
-  @param  PtrTrack                    VARIABLE_POINTER_TRACK structure for output,\r
+  @param[in]   VariableName           Name of the variable to be found.\r
+  @param[in]   VendorGuid             Vendor GUID to be found.\r
+  @param[out]  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
+  @param[in]   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[in]   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
@@ -959,92 +1312,44 @@ 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
-\r
-  //\r
-  // 0: Volatile, 1: 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
-  //\r
-  VariableStoreHeader[0]  = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);\r
-  VariableStoreHeader[1]  = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase);\r
-\r
-  //\r
-  // Start Pointers for the variable.\r
-  // Actual Data Pointer where data can be written.\r
-  //\r
-  Variable[0] = GetStartPointer (VariableStoreHeader[0]);\r
-  Variable[1] = GetStartPointer (VariableStoreHeader[1]);\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
-  // Find the variable by walk through volatile and then non-volatile variable store\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 algorithm.\r
   //\r
-  InDeletedVariable     = NULL;\r
-  InDeletedStorageIndex = 0;\r
-  for (Index = 0; Index < 2; Index++) {\r
-    while ((Variable[Index] < GetEndPointer (VariableStoreHeader[Index])) && IsValidVariableHeader (Variable[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) != 0)) {\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])) == 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
-              }\r
-            }\r
-          }\r
-        }\r
-      }\r
+  VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) Global->VolatileVariableBase;\r
+  VariableStoreHeader[VariableStoreTypeHob]      = (VARIABLE_STORE_HEADER *) (UINTN) Global->HobVariableBase;\r
+  VariableStoreHeader[VariableStoreTypeNv]       = mNvVariableCache;\r
 \r
-      Variable[Index] = GetNextVariablePtr (Variable[Index]);\r
+  //\r
+  // Find the variable by walk through HOB, volatile and non-volatile variable store.\r
+  //\r
+  for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {\r
+    if (VariableStoreHeader[Type] == NULL) {\r
+      continue;\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
+\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
-  PtrTrack->CurrPtr = NULL;\r
   return EFI_NOT_FOUND;\r
 }\r
 \r
@@ -1071,25 +1376,22 @@ FindVariable (
   @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
+  @retval The index of language in the language codes.\r
 \r
 **/\r
 UINTN\r
-EFIAPI\r
 GetIndexFromSupportedLangCodes(\r
   IN  CHAR8            *SupportedLang,\r
   IN  CHAR8            *Lang,\r
   IN  BOOLEAN          Iso639Language\r
-  ) \r
+  )\r
 {\r
   UINTN    Index;\r
-  UINT32   CompareLength;\r
-  CHAR8    *Supported;\r
+  UINT   CompareLength;\r
+  UINTN    LanguageLength;\r
 \r
-  Index = 0;\r
-  Supported = SupportedLang;\r
   if (Iso639Language) {\r
-    CompareLength = 3;\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
@@ -1105,20 +1407,26 @@ GetIndexFromSupportedLangCodes(
     //\r
     // Compare RFC4646 language code\r
     //\r
-    while (*Supported != '\0') {\r
+    Index = 0;\r
+    for (LanguageLength = 0; Lang[LanguageLength] != '\0'; LanguageLength++);\r
+\r
+    for (Index = 0; *SupportedLang != '\0'; Index++, SupportedLang += CompareLength) {\r
       //\r
-      // take semicolon as delimitation, sequentially traverse supported language codes.\r
+      // Skip ';' characters in SupportedLang\r
       //\r
-      for (CompareLength = 0; *Supported != ';' && *Supported != '\0'; CompareLength++) {\r
-        Supported++;\r
-      }\r
-      if (AsciiStrnCmp (Lang, Supported - CompareLength, CompareLength) == 0) {\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
-      Index++;\r
     }\r
     ASSERT (FALSE);\r
     return 0;\r
@@ -1128,7 +1436,7 @@ GetIndexFromSupportedLangCodes(
 /**\r
   Get language string from supported language codes according to index.\r
 \r
-  This code is used to get corresponding language string in supported language codes. It can handle\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
@@ -1145,14 +1453,13 @@ GetIndexFromSupportedLangCodes(
   The return value is "fr".\r
 \r
   @param  SupportedLang               Platform supported language codes.\r
-  @param  Index                       the index in 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
+  @retval The language string in the language codes.\r
 \r
 **/\r
 CHAR8 *\r
-EFIAPI\r
 GetLangFromSupportedLangCodes (\r
   IN  CHAR8            *SupportedLang,\r
   IN  UINTN            Index,\r
@@ -1160,25 +1467,25 @@ GetLangFromSupportedLangCodes (
 )\r
 {\r
   UINTN    SubIndex;\r
-  UINT32   CompareLength;\r
+  UINT   CompareLength;\r
   CHAR8    *Supported;\r
 \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
-    // As this code will be invoked in RUNTIME, therefore there is not memory allocate/free operation.\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 = 3;\r
-    SetMem (mVariableModuleGlobal->Lang, sizeof(mVariableModuleGlobal->Lang), 0);\r
+    CompareLength = ISO_639_2_ENTRY_SIZE;\r
+    mVariableModuleGlobal->Lang[CompareLength] = '\0';\r
     return CopyMem (mVariableModuleGlobal->Lang, SupportedLang + Index * CompareLength, CompareLength);\r
-      \r
+\r
   } else {\r
     while (TRUE) {\r
       //\r
-      // take semicolon as delimitation, sequentially traverse supported language codes.\r
+      // Take semicolon as delimitation, sequentially traverse supported language codes.\r
       //\r
       for (CompareLength = 0; *Supported != ';' && *Supported != '\0'; CompareLength++) {\r
         Supported++;\r
@@ -1193,165 +1500,635 @@ GetLangFromSupportedLangCodes (
       }\r
       if (SubIndex == Index) {\r
         //\r
-        // according to the index of Lang string in SupportedLang string to get the language.\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
-        SetMem (mVariableModuleGlobal->PlatformLang, sizeof (mVariableModuleGlobal->PlatformLang), 0);\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
-  Hook the operations in PlatformLangCodes, LangCodes, PlatformLang and Lang.\r
-\r
-  When setting Lang/LangCodes, simultaneously update PlatformLang/PlatformLangCodes.\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
-  According to UEFI spec, PlatformLangCodes/LangCodes are only set once in firmware initialization,\r
+**/\r
+CHAR8 *\r
+EFIAPI\r
+VariableGetBestLanguage (\r
+  IN CONST CHAR8  *SupportedLanguages,\r
+  IN BOOLEAN      Iso639Language,\r
+  ...\r
+  )\r
+{\r
+  VA_LIST      Args;\r
+  CHAR8        *Language;\r
+  UINTN        CompareLength;\r
+  UINTN        LanguageLength;\r
+  CONST CHAR8  *Supported;\r
+  CHAR8        *Buffer;\r
+\r
+  if (SupportedLanguages == NULL) {\r
+    return NULL;\r
+  }\r
+\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
+    // 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
+  // No matches were found\r
+  //\r
+  return NULL;\r
+}\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
+  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
+  @param[in] Attributes         Variable attributes for Variable entries.\r
+  @param[in] Marker             VA_LIST style variable argument list.\r
+                                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
+CheckRemainingSpaceForConsistencyInternal (\r
+  IN UINT32                     Attributes,\r
+  IN VA_LIST                    Marker\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_COPY (Args, Marker);\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 (GetVariableHeaderSize () + VarNameSize + VarDataSize);\r
+\r
+    TotalNeededSize += VariableEntry->VariableSize;\r
+    VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);\r
+  }\r
+  VA_END  (Args);\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_COPY (Args, Marker);\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
+  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
+  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
+  @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
+  VA_LIST Marker;\r
+  BOOLEAN Return;\r
+\r
+  VA_START (Marker, Attributes);\r
+\r
+  Return = CheckRemainingSpaceForConsistencyInternal (Attributes, Marker);\r
+\r
+  VA_END (Marker);\r
+\r
+  return Return;\r
+}\r
+\r
+/**\r
+  Hook the operations in PlatformLangCodes, LangCodes, PlatformLang and Lang.\r
+\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
+  @param[in] VariableName       Name of variable.\r
 \r
-  @param[in] Data               Variable data\r
+  @param[in] Data               Variable data.\r
 \r
-  @param[in] DataSize           Size of data. 0 means delete\r
+  @param[in] DataSize           Size of data. 0 means delete.\r
 \r
-  @retval EFI_SUCCESS  auto update operation is successful.\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
-AutoUpdateLangVariable(\r
+AutoUpdateLangVariable (\r
   IN  CHAR16             *VariableName,\r
   IN  VOID               *Data,\r
   IN  UINTN              DataSize\r
   )\r
 {\r
-  EFI_STATUS     Status;\r
-  CHAR8          *BestPlatformLang;\r
-  CHAR8          *BestLang;\r
-  UINTN          Index;\r
-  UINT32         Attributes;\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
   //\r
-  // According to UEFI spec, "Lang" and "PlatformLang" is NV|BS|RT attributions.\r
+  // Don't do updates for delete operation\r
   //\r
-  Attributes = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS;\r
+  if (DataSize == 0) {\r
+    return EFI_SUCCESS;\r
+  }\r
+\r
+  SetLanguageCodes = FALSE;\r
 \r
-  if (StrCmp (VariableName, L"PlatformLangCodes") == 0) {\r
+  if (StrCmp (VariableName, EFI_PLATFORM_LANG_CODES_VARIABLE_NAME) == 0) {\r
     //\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
+    // PlatformLangCodes is a volatile variable, so it can not be updated at runtime.\r
     //\r
-    AsciiStrnCpy (mVariableModuleGlobal->PlatformLangCodes, Data, DataSize);\r
-  } else if (StrCmp (VariableName, L"LangCodes") == 0) {\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
+    // 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
-    AsciiStrnCpy (mVariableModuleGlobal->LangCodes, Data, DataSize);\r
-  } else if ((StrCmp (VariableName, L"PlatformLang") == 0) && (DataSize != 0)) {\r
-    ASSERT (AsciiStrLen (mVariableModuleGlobal->PlatformLangCodes) != 0);\r
+    if (mVariableModuleGlobal->PlatformLangCodes != NULL) {\r
+      FreePool (mVariableModuleGlobal->PlatformLangCodes);\r
+    }\r
+    mVariableModuleGlobal->PlatformLangCodes = AllocateRuntimeCopyPool (DataSize, Data);\r
+    ASSERT (mVariableModuleGlobal->PlatformLangCodes != NULL);\r
 \r
     //\r
-    // When setting PlatformLang, firstly get most matched language string from supported language codes.\r
+    // PlatformLang holds a single language from PlatformLangCodes,\r
+    // so the size of PlatformLangCodes is enough for the PlatformLang.\r
     //\r
-    BestPlatformLang = GetBestLanguage(mVariableModuleGlobal->PlatformLangCodes, FALSE, Data, NULL);\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
-    // Get the corresponding index in language codes.\r
+    // LangCodes is a volatile variable, so it can not be updated at runtime.\r
     //\r
-    Index = GetIndexFromSupportedLangCodes(mVariableModuleGlobal->PlatformLangCodes, BestPlatformLang, FALSE);\r
+    if (AtRuntime ()) {\r
+      return EFI_WRITE_PROTECTED;\r
+    }\r
+\r
+    SetLanguageCodes = TRUE;\r
 \r
     //\r
-    // Get the corresponding ISO639 language tag according to RFC4646 language tag.\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
-    BestLang = GetLangFromSupportedLangCodes(mVariableModuleGlobal->LangCodes, Index, TRUE);\r
+    if (mVariableModuleGlobal->LangCodes != NULL) {\r
+      FreePool (mVariableModuleGlobal->LangCodes);\r
+    }\r
+    mVariableModuleGlobal->LangCodes = AllocateRuntimeCopyPool (DataSize, Data);\r
+    ASSERT (mVariableModuleGlobal->LangCodes != NULL);\r
+  }\r
 \r
+  if (SetLanguageCodes\r
+      && (mVariableModuleGlobal->PlatformLangCodes != NULL)\r
+      && (mVariableModuleGlobal->LangCodes != NULL)) {\r
     //\r
-    // Successfully convert PlatformLang to Lang, and set the BestLang value into Lang variable simultaneously.\r
+    // Update Lang if PlatformLang is already set\r
+    // Update PlatformLang if Lang is already set\r
     //\r
-    FindVariable(L"Lang", &gEfiGlobalVariableGuid, &Variable, (VARIABLE_GLOBAL *)mVariableModuleGlobal);\r
-\r
-    Status = UpdateVariable(L"Lang", &gEfiGlobalVariableGuid, \r
-                    BestLang, ISO_639_2_ENTRY_SIZE + 1, Attributes, &Variable);\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     = DataSizeOfVariable (Variable.CurrPtr);\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     = DataSizeOfVariable (Variable.CurrPtr);\r
+      } else {\r
+        //\r
+        // Neither PlatformLang nor Lang is set, directly return\r
+        //\r
+        return EFI_SUCCESS;\r
+      }\r
+    }\r
+  }\r
 \r
-    DEBUG((EFI_D_INFO, "Variable Driver Auto Update PlatformLang, PlatformLang:%a, Lang:%a\n", BestPlatformLang, BestLang));\r
+  Status = EFI_SUCCESS;\r
 \r
-    ASSERT_EFI_ERROR(Status);\r
-    \r
-  } else if ((StrCmp (VariableName, L"Lang") == 0) && (DataSize != 0)) {\r
-    ASSERT (AsciiStrLen (mVariableModuleGlobal->LangCodes) != 0);\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
-    // When setting Lang, firstly get most matched language string from supported language codes.\r
+    // Update Lang when PlatformLangCodes/LangCodes were set.\r
     //\r
-    BestLang = GetBestLanguage(mVariableModuleGlobal->LangCodes, TRUE, Data, NULL);\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 index in language codes.\r
-    //\r
-    Index = GetIndexFromSupportedLangCodes(mVariableModuleGlobal->LangCodes, BestLang, TRUE);\r
+        //\r
+        // Get the corresponding ISO639 language tag according to RFC4646 language tag.\r
+        //\r
+        BestLang = GetLangFromSupportedLangCodes (mVariableModuleGlobal->LangCodes, Index, TRUE);\r
 \r
-    //\r
-    // Get the corresponding RFC4646 language tag according to ISO639 language tag.\r
-    //\r
-    BestPlatformLang = GetLangFromSupportedLangCodes(mVariableModuleGlobal->PlatformLangCodes, Index, FALSE);\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, 0, 0, &Variable, NULL);\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
-    // Successfully convert Lang to PlatformLang, and set the BestPlatformLang value into PlatformLang variable simultaneously.\r
+    // Update PlatformLang when PlatformLangCodes/LangCodes were set.\r
     //\r
-    FindVariable(L"PlatformLang", &gEfiGlobalVariableGuid, &Variable, (VARIABLE_GLOBAL *)mVariableModuleGlobal);\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
+        //\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
+          //\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(L"PlatformLang", &gEfiGlobalVariableGuid, \r
-                    BestPlatformLang, AsciiStrSize (BestPlatformLang), Attributes, &Variable);\r
+          Status = UpdateVariable (EFI_PLATFORM_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, BestPlatformLang,\r
+                                   AsciiStrSize (BestPlatformLang), Attributes, 0, 0, &Variable, NULL);\r
+        }\r
 \r
-    DEBUG((EFI_D_INFO, "Variable Driver Auto Update Lang, Lang:%a, PlatformLang:%a\n", BestLang, BestPlatformLang));\r
-    ASSERT_EFI_ERROR(Status);\r
+        DEBUG ((EFI_D_INFO, "Variable Driver Auto Update Lang, Lang:%a, PlatformLang:%a Status: %r\n", BestLang, BestPlatformLang, Status));\r
+      }\r
+    }\r
+  }\r
+\r
+  if (SetLanguageCodes) {\r
+    //\r
+    // Continue to set PlatformLangCodes or LangCodes.\r
+    //\r
+    return EFI_SUCCESS;\r
+  } else {\r
+    return Status;\r
   }\r
-  return EFI_SUCCESS;\r
 }\r
 \r
 /**\r
-  Update the variable region with Variable information. These are the same \r
-  arguments as the EFI Variable services.\r
+  Compare two EFI_TIME data.\r
 \r
-  @param[in] VariableName       Name of variable\r
 \r
-  @param[in] VendorGuid         Guid of variable\r
+  @param FirstTime           A pointer to the first EFI_TIME data.\r
+  @param SecondTime          A pointer to the second EFI_TIME data.\r
 \r
-  @param[in] Data               Variable data\r
+  @retval  TRUE              The FirstTime is not later than the SecondTime.\r
+  @retval  FALSE             The FirstTime is later than the SecondTime.\r
 \r
-  @param[in] DataSize           Size of data. 0 means delete\r
+**/\r
+BOOLEAN\r
+VariableCompareTimeStampInternal (\r
+  IN EFI_TIME               *FirstTime,\r
+  IN EFI_TIME               *SecondTime\r
+  )\r
+{\r
+  if (FirstTime->Year != SecondTime->Year) {\r
+    return (BOOLEAN) (FirstTime->Year < SecondTime->Year);\r
+  } else if (FirstTime->Month != SecondTime->Month) {\r
+    return (BOOLEAN) (FirstTime->Month < SecondTime->Month);\r
+  } else if (FirstTime->Day != SecondTime->Day) {\r
+    return (BOOLEAN) (FirstTime->Day < SecondTime->Day);\r
+  } else if (FirstTime->Hour != SecondTime->Hour) {\r
+    return (BOOLEAN) (FirstTime->Hour < SecondTime->Hour);\r
+  } else if (FirstTime->Minute != SecondTime->Minute) {\r
+    return (BOOLEAN) (FirstTime->Minute < SecondTime->Minute);\r
+  }\r
 \r
-  @param[in] Attributes         Attribues of the variable\r
+  return (BOOLEAN) (FirstTime->Second <= SecondTime->Second);\r
+}\r
 \r
-  @param[in] Variable           The variable information which is used to keep track of variable usage.\r
+/**\r
+  Update the variable region with Variable information. If EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS is set,\r
+  index of associated public key is needed.\r
+\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         Attributes of the variable.\r
+  @param[in] KeyIndex           Index of associated public key.\r
+  @param[in] MonotonicCount     Value of associated monotonic count.\r
+  @param[in, out] CacheVariable The variable information which is used to keep track of variable usage.\r
+  @param[in] TimeStamp          Value of associated TimeStamp.\r
 \r
   @retval EFI_SUCCESS           The update operation is success.\r
-\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
 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      VARIABLE_POINTER_TRACK *Variable\r
+  IN      CHAR16                      *VariableName,\r
+  IN      EFI_GUID                    *VendorGuid,\r
+  IN      VOID                        *Data,\r
+  IN      UINTN                       DataSize,\r
+  IN      UINT32                      Attributes      OPTIONAL,\r
+  IN      UINT32                      KeyIndex        OPTIONAL,\r
+  IN      UINT64                      MonotonicCount  OPTIONAL,\r
+  IN OUT  VARIABLE_POINTER_TRACK      *CacheVariable,\r
+  IN      EFI_TIME                    *TimeStamp      OPTIONAL\r
   )\r
 {\r
   EFI_STATUS                          Status;\r
   VARIABLE_HEADER                     *NextVariable;\r
   UINTN                               ScratchSize;\r
-  UINTN                               NonVolatileVarableStoreSize;\r
+  UINTN                               MaxDataSize;\r
   UINTN                               VarNameOffset;\r
   UINTN                               VarDataOffset;\r
   UINTN                               VarNameSize;\r
@@ -1359,21 +2136,108 @@ UpdateVariable (
   BOOLEAN                             Volatile;\r
   EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL  *Fvb;\r
   UINT8                               State;\r
-  BOOLEAN                             Reclaimed;\r
+  VARIABLE_POINTER_TRACK              *Variable;\r
+  VARIABLE_POINTER_TRACK              NvVariable;\r
+  VARIABLE_STORE_HEADER               *VariableStoreHeader;\r
+  UINTN                               CacheOffset;\r
+  UINT8                               *BufferForMerge;\r
+  UINTN                               MergedBufSize;\r
+  BOOLEAN                             DataReady;\r
+  UINTN                               DataOffset;\r
+  BOOLEAN                             IsCommonVariable;\r
+  BOOLEAN                             IsCommonUserVariable;\r
+  AUTHENTICATED_VARIABLE_HEADER       *AuthVariable;\r
+\r
+  if (mVariableModuleGlobal->FvbInstance == NULL) {\r
+    //\r
+    // The FVB protocol is not ready, so the EFI_VARIABLE_WRITE_ARCH_PROTOCOL is not installed.\r
+    //\r
+    if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {\r
+      //\r
+      // Trying to update NV variable prior to the installation of EFI_VARIABLE_WRITE_ARCH_PROTOCOL\r
+      //\r
+      DEBUG ((EFI_D_ERROR, "Update NV variable before EFI_VARIABLE_WRITE_ARCH_PROTOCOL ready - %r\n", EFI_NOT_AVAILABLE_YET));\r
+      return EFI_NOT_AVAILABLE_YET;\r
+    } else if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {\r
+      //\r
+      // Trying to update volatile authenticated variable prior to the installation of EFI_VARIABLE_WRITE_ARCH_PROTOCOL\r
+      // The authenticated variable perhaps is not initialized, just return here.\r
+      //\r
+      DEBUG ((EFI_D_ERROR, "Update AUTH variable before EFI_VARIABLE_WRITE_ARCH_PROTOCOL ready - %r\n", EFI_NOT_AVAILABLE_YET));\r
+      return EFI_NOT_AVAILABLE_YET;\r
+    }\r
+  }\r
+\r
+  //\r
+  // Check if CacheVariable points to the variable in variable HOB.\r
+  // If yes, let CacheVariable points to the variable in NV variable cache.\r
+  //\r
+  if ((CacheVariable->CurrPtr != NULL) &&\r
+      (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) &&\r
+      (CacheVariable->StartPtr == GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase))\r
+     ) {\r
+    CacheVariable->StartPtr = GetStartPointer (mNvVariableCache);\r
+    CacheVariable->EndPtr   = GetEndPointer   (mNvVariableCache);\r
+    CacheVariable->Volatile = FALSE;\r
+    Status = FindVariableEx (VariableName, VendorGuid, FALSE, CacheVariable);\r
+    if (CacheVariable->CurrPtr == NULL || EFI_ERROR (Status)) {\r
+      //\r
+      // There is no matched variable in NV variable cache.\r
+      //\r
+      if ((((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && (DataSize == 0)) || (Attributes == 0)) {\r
+        //\r
+        // It is to delete variable,\r
+        // go to delete this variable in variable HOB and\r
+        // try to flush other variables from HOB to flash.\r
+        //\r
+        UpdateVariableInfo (VariableName, VendorGuid, FALSE, FALSE, FALSE, TRUE, FALSE);\r
+        FlushHobVariableToFlash (VariableName, VendorGuid);\r
+        return EFI_SUCCESS;\r
+      }\r
+    }\r
+  }\r
+\r
+  if ((CacheVariable->CurrPtr == NULL) || CacheVariable->Volatile) {\r
+    Variable = CacheVariable;\r
+  } else {\r
+    //\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
+    VariableStoreHeader  = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase);\r
+    Variable = &NvVariable;\r
+    Variable->StartPtr = GetStartPointer (VariableStoreHeader);\r
+    Variable->EndPtr   = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->EndPtr - (UINTN)CacheVariable->StartPtr));\r
+\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
+    Variable->Volatile = FALSE;\r
+  }\r
+\r
+  Fvb       = mVariableModuleGlobal->FvbInstance;\r
 \r
-  Fvb               = mVariableModuleGlobal->FvbInstance;\r
-  Reclaimed         = FALSE;\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 = mVariableModuleGlobal->ScratchBufferSize;\r
+  SetMem (NextVariable, ScratchSize, 0xff);\r
+  DataReady = FALSE;\r
 \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
-      // the volatile is ReadOnly, and SetVariable should be aborted and \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
@@ -1381,53 +2245,144 @@ UpdateVariable (
         goto Done;\r
       }\r
       //\r
-      // Only variable have NV attribute can be updated/deleted in Runtime\r
+      // Only variable that have NV attributes can be updated/deleted in Runtime.\r
+      //\r
+      if ((CacheVariable->CurrPtr->Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {\r
+        Status = EFI_INVALID_PARAMETER;\r
+        goto Done;\r
+      }\r
+\r
+      //\r
+      // Only variable that have RT attributes can be updated/deleted in Runtime.\r
       //\r
-      if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {\r
+      if ((CacheVariable->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) {\r
         Status = EFI_INVALID_PARAMETER;\r
-        goto Done;      \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
+    // When the EFI_VARIABLE_APPEND_WRITE attribute is set, DataSize of zero will\r
+    // not delete the variable.\r
     //\r
-    if (DataSize == 0 || (Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0) {    \r
-      State = Variable->CurrPtr->State;\r
-      State &= VAR_DELETED;\r
-\r
-      Status = UpdateVariableStore (\r
-                 &mVariableModuleGlobal->VariableGlobal,\r
+    if ((((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && (DataSize == 0))|| ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0)) {\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
+        ASSERT (CacheVariable->InDeletedTransitionPtr != NULL);\r
+        State = CacheVariable->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
+            CacheVariable->InDeletedTransitionPtr->State = State;\r
+          }\r
+        } else {\r
+          goto Done;\r
+        }\r
+      }\r
+\r
+      State = CacheVariable->CurrPtr->State;\r
+      State &= VAR_DELETED;\r
+\r
+      Status = UpdateVariableStore (\r
+                 &mVariableModuleGlobal->VariableGlobal,\r
                  Variable->Volatile,\r
                  FALSE,\r
                  Fvb,\r
                  (UINTN) &Variable->CurrPtr->State,\r
                  sizeof (UINT8),\r
                  &State\r
-                 ); \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
+      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
-      \r
-      UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE);\r
+    if (DataSizeOfVariable (CacheVariable->CurrPtr) == DataSize &&\r
+        (CompareMem (Data, GetVariableDataPtr (CacheVariable->CurrPtr), DataSize) == 0) &&\r
+        ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) &&\r
+        (TimeStamp == NULL)) {\r
+      //\r
+      // Variable content unchanged and no need to update timestamp, just return.\r
+      //\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 ((CacheVariable->CurrPtr->State == VAR_ADDED) ||\r
+               (CacheVariable->CurrPtr->State == (VAR_ADDED & VAR_IN_DELETED_TRANSITION))) {\r
+\r
+      //\r
+      // EFI_VARIABLE_APPEND_WRITE attribute only effects for existing variable.\r
+      //\r
+      if ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0) {\r
+        //\r
+        // NOTE: From 0 to DataOffset of NextVariable is reserved for Variable Header and Name.\r
+        // From DataOffset of NextVariable is to save the existing variable data.\r
+        //\r
+        DataOffset = GetVariableDataOffset (CacheVariable->CurrPtr);\r
+        BufferForMerge = (UINT8 *) ((UINTN) NextVariable + DataOffset);\r
+        CopyMem (BufferForMerge, (UINT8 *) ((UINTN) CacheVariable->CurrPtr + DataOffset), DataSizeOfVariable (CacheVariable->CurrPtr));\r
+\r
+        //\r
+        // Set Max Common/Auth Variable Data Size as default MaxDataSize.\r
+        //\r
+        if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {\r
+          MaxDataSize = mVariableModuleGlobal->MaxAuthVariableSize - DataOffset;\r
+        } else {\r
+          MaxDataSize = mVariableModuleGlobal->MaxVariableSize - DataOffset;\r
+        }\r
+\r
+        //\r
+        // Append the new data to the end of existing data.\r
+        // Max Harware error record variable data size is different from common/auth variable.\r
+        //\r
+        if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+          MaxDataSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - DataOffset;\r
+        }\r
+\r
+        if (DataSizeOfVariable (CacheVariable->CurrPtr) + DataSize > MaxDataSize) {\r
+          //\r
+          // Existing data size + new data size exceed maximum variable size limitation.\r
+          //\r
+          Status = EFI_INVALID_PARAMETER;\r
+          goto Done;\r
+        }\r
+        CopyMem ((UINT8*) ((UINTN) BufferForMerge + DataSizeOfVariable (CacheVariable->CurrPtr)), Data, DataSize);\r
+        MergedBufSize = DataSizeOfVariable (CacheVariable->CurrPtr) + DataSize;\r
+\r
+        //\r
+        // BufferForMerge(from DataOffset of NextVariable) has included the merged existing and new data.\r
+        //\r
+        Data      = BufferForMerge;\r
+        DataSize  = MergedBufSize;\r
+        DataReady = TRUE;\r
+      }\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 = CacheVariable->CurrPtr->State;\r
       State &= VAR_IN_DELETED_TRANSITION;\r
 \r
       Status = UpdateVariableStore (\r
@@ -1438,74 +2393,112 @@ UpdateVariable (
                  (UINTN) &Variable->CurrPtr->State,\r
                  sizeof (UINT8),\r
                  &State\r
-                 );      \r
+                 );\r
       if (EFI_ERROR (Status)) {\r
-        goto Done;  \r
-      } \r
-    }    \r
+        goto Done;\r
+      }\r
+      if (!Variable->Volatile) {\r
+        CacheVariable->CurrPtr->State = State;\r
+      }\r
+    }\r
   } else {\r
     //\r
-    // Not found existing variable. Create a new variable\r
-    //  \r
-    \r
+    // Not found existing variable. Create a new variable.\r
+    //\r
+\r
+    if ((DataSize == 0) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0)) {\r
+      Status = EFI_SUCCESS;\r
+      goto Done;\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
       goto Done;\r
     }\r
-        \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
+    }\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
-  // 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(FixedPcdGet32(PcdMaxVariableSize), FixedPcdGet32(PcdMaxHardwareErrorVariableSize));\r
-\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
+  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {\r
+    AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) NextVariable;\r
+    AuthVariable->PubKeyIndex    = KeyIndex;\r
+    AuthVariable->MonotonicCount = MonotonicCount;\r
+    ZeroMem (&AuthVariable->TimeStamp, sizeof (EFI_TIME));\r
+\r
+    if (((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) &&\r
+        (TimeStamp != NULL)) {\r
+      if ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) {\r
+        CopyMem (&AuthVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));\r
+      } else {\r
+        //\r
+        // In the case when the EFI_VARIABLE_APPEND_WRITE attribute is set, only\r
+        // when the new TimeStamp value is later than the current timestamp associated\r
+        // with the variable, we need associate the new timestamp with the updated value.\r
+        //\r
+        if (Variable->CurrPtr != NULL) {\r
+          if (VariableCompareTimeStampInternal (&(((AUTHENTICATED_VARIABLE_HEADER *) CacheVariable->CurrPtr)->TimeStamp), TimeStamp)) {\r
+            CopyMem (&AuthVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));\r
+          }\r
+        }\r
+      }\r
+    }\r
+  }\r
+\r
+  //\r
+  // The EFI_VARIABLE_APPEND_WRITE attribute will never be set in the returned\r
+  // Attributes bitmask parameter of a GetVariable() call.\r
+  //\r
+  NextVariable->Attributes  = Attributes & (~EFI_VARIABLE_APPEND_WRITE);\r
+\r
+  VarNameOffset                 = GetVariableHeaderSize ();\r
+  VarNameSize                   = StrSize (VariableName);\r
   CopyMem (\r
     (UINT8 *) ((UINTN) NextVariable + VarNameOffset),\r
     VariableName,\r
     VarNameSize\r
     );\r
   VarDataOffset = VarNameOffset + VarNameSize + GET_PAD_SIZE (VarNameSize);\r
-  CopyMem (\r
-    (UINT8 *) ((UINTN) NextVariable + VarDataOffset),\r
-    Data,\r
-    DataSize\r
-    );\r
-  CopyMem (&NextVariable->VendorGuid, VendorGuid, sizeof (EFI_GUID));\r
+\r
+  //\r
+  // If DataReady is TRUE, it means the variable data has been saved into\r
+  // NextVariable during EFI_VARIABLE_APPEND_WRITE operation preparation.\r
+  //\r
+  if (!DataReady) {\r
+    CopyMem (\r
+      (UINT8 *) ((UINTN) NextVariable + VarDataOffset),\r
+      Data,\r
+      DataSize\r
+      );\r
+  }\r
+\r
+  CopyMem (GetVendorGuidPtr (NextVariable), VendorGuid, sizeof (EFI_GUID));\r
   //\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
+  SetNameSizeOfVariable (NextVariable, VarNameSize);\r
+  SetDataSizeOfVariable (NextVariable, DataSize);\r
 \r
   //\r
   // The actual size of the variable that stores in storage should\r
@@ -1514,55 +2507,80 @@ UpdateVariable (
   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
-    NonVolatileVarableStoreSize = ((VARIABLE_STORE_HEADER *)(UINTN)(mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase))->Size;\r
-    if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) \r
-      && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > FixedPcdGet32(PcdHwErrStorageSize)))\r
-      || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0) \r
-      && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > NonVolatileVarableStoreSize - sizeof (VARIABLE_STORE_HEADER) - FixedPcdGet32(PcdHwErrStorageSize)))) {\r
-      if (EfiAtRuntime ()) {\r
+\r
+    IsCommonVariable = FALSE;\r
+    IsCommonUserVariable = FALSE;\r
+    if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0) {\r
+      IsCommonVariable = TRUE;\r
+      IsCommonUserVariable = IsUserVariable (NextVariable);\r
+    }\r
+    if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0)\r
+      && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize)))\r
+      || (IsCommonVariable && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > mVariableModuleGlobal->CommonVariableSpace))\r
+      || (IsCommonVariable && AtRuntime () && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > mVariableModuleGlobal->CommonRuntimeVariableSpace))\r
+      || (IsCommonUserVariable && ((VarSize + mVariableModuleGlobal->CommonUserVariableTotalSize) > mVariableModuleGlobal->CommonMaxUserVariableSpace))) {\r
+      if (AtRuntime ()) {\r
+        if (IsCommonUserVariable && ((VarSize + mVariableModuleGlobal->CommonUserVariableTotalSize) > mVariableModuleGlobal->CommonMaxUserVariableSpace)) {\r
+          RecordVarErrorFlag (VAR_ERROR_FLAG_USER_ERROR, VariableName, VendorGuid, Attributes, VarSize);\r
+        }\r
+        if (IsCommonVariable && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > mVariableModuleGlobal->CommonRuntimeVariableSpace)) {\r
+          RecordVarErrorFlag (VAR_ERROR_FLAG_SYSTEM_ERROR, VariableName, VendorGuid, Attributes, VarSize);\r
+        }\r
         Status = EFI_OUT_OF_RESOURCES;\r
         goto Done;\r
       }\r
       //\r
-      // Perform garbage collection & reclaim operation\r
-      //\r
-      Status = Reclaim (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase, \r
-                        &mVariableModuleGlobal->NonVolatileLastVariableOffset, 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 ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) \r
-        && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > FixedPcdGet32(PcdHwErrStorageSize)))\r
-        || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0) \r
-        && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > NonVolatileVarableStoreSize - sizeof (VARIABLE_STORE_HEADER) - FixedPcdGet32(PcdHwErrStorageSize)))) {\r
-        Status = EFI_OUT_OF_RESOURCES;\r
-        goto Done;\r
+      Status = Reclaim (\r
+                 mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,\r
+                 &mVariableModuleGlobal->NonVolatileLastVariableOffset,\r
+                 FALSE,\r
+                 Variable,\r
+                 NextVariable,\r
+                 HEADER_ALIGN (VarSize)\r
+                 );\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
+      } else {\r
+        if (IsCommonUserVariable && ((VarSize + mVariableModuleGlobal->CommonUserVariableTotalSize) > mVariableModuleGlobal->CommonMaxUserVariableSpace)) {\r
+          RecordVarErrorFlag (VAR_ERROR_FLAG_USER_ERROR, VariableName, VendorGuid, Attributes, VarSize);\r
+        }\r
+        if (IsCommonVariable && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > mVariableModuleGlobal->CommonVariableSpace)) {\r
+          RecordVarErrorFlag (VAR_ERROR_FLAG_SYSTEM_ERROR, VariableName, VendorGuid, Attributes, VarSize);\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
+    // 2. Set variable state to header valid\r
     // 3. Write variable data\r
     // 4. Set variable state to valid\r
     //\r
     //\r
     // Step 1:\r
     //\r
+    CacheOffset = mVariableModuleGlobal->NonVolatileLastVariableOffset;\r
     Status = UpdateVariableStore (\r
                &mVariableModuleGlobal->VariableGlobal,\r
                FALSE,\r
                TRUE,\r
                Fvb,\r
                mVariableModuleGlobal->NonVolatileLastVariableOffset,\r
-               sizeof (VARIABLE_HEADER),\r
+               (UINT32) GetVariableHeaderSize (),\r
                (UINT8 *) NextVariable\r
                );\r
 \r
@@ -1579,9 +2597,9 @@ UpdateVariable (
                FALSE,\r
                TRUE,\r
                Fvb,\r
-               mVariableModuleGlobal->NonVolatileLastVariableOffset,\r
-               sizeof (VARIABLE_HEADER),\r
-               (UINT8 *) NextVariable\r
+               mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),\r
+               sizeof (UINT8),\r
+               &NextVariable->State\r
                );\r
 \r
     if (EFI_ERROR (Status)) {\r
@@ -1595,9 +2613,9 @@ UpdateVariable (
                FALSE,\r
                TRUE,\r
                Fvb,\r
-               mVariableModuleGlobal->NonVolatileLastVariableOffset + sizeof (VARIABLE_HEADER),\r
-               (UINT32) VarSize - sizeof (VARIABLE_HEADER),\r
-               (UINT8 *) NextVariable + sizeof (VARIABLE_HEADER)\r
+               mVariableModuleGlobal->NonVolatileLastVariableOffset + GetVariableHeaderSize (),\r
+               (UINT32) (VarSize - GetVariableHeaderSize ()),\r
+               (UINT8 *) NextVariable + GetVariableHeaderSize ()\r
                );\r
 \r
     if (EFI_ERROR (Status)) {\r
@@ -1612,9 +2630,9 @@ UpdateVariable (
                FALSE,\r
                TRUE,\r
                Fvb,\r
-               mVariableModuleGlobal->NonVolatileLastVariableOffset,\r
-               sizeof (VARIABLE_HEADER),\r
-               (UINT8 *) NextVariable\r
+               mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),\r
+               sizeof (UINT8),\r
+               &NextVariable->State\r
                );\r
 \r
     if (EFI_ERROR (Status)) {\r
@@ -1627,33 +2645,44 @@ UpdateVariable (
       mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VarSize);\r
     } else {\r
       mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VarSize);\r
+      if (IsCommonUserVariable) {\r
+        mVariableModuleGlobal->CommonUserVariableTotalSize += HEADER_ALIGN (VarSize);\r
+      }\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
-    //      \r
+    // Create a volatile variable.\r
+    //\r
     Volatile = TRUE;\r
 \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, \r
-                          &mVariableModuleGlobal->VolatileLastVariableOffset, 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 + mVariableModuleGlobal->VolatileLastVariableOffset) >\r
-            ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase)))->Size\r
-            ) {\r
-        Status = EFI_OUT_OF_RESOURCES;\r
-        goto Done;\r
+      Status = Reclaim (\r
+                 mVariableModuleGlobal->VariableGlobal.VolatileVariableBase,\r
+                 &mVariableModuleGlobal->VolatileLastVariableOffset,\r
+                 TRUE,\r
+                 Variable,\r
+                 NextVariable,\r
+                 HEADER_ALIGN (VarSize)\r
+                 );\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
-      Reclaimed = TRUE;\r
+      goto Done;\r
     }\r
 \r
     NextVariable->State = VAR_ADDED;\r
@@ -1675,9 +2704,35 @@ UpdateVariable (
   }\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
+  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
+      ASSERT (CacheVariable->InDeletedTransitionPtr != NULL);\r
+      State = CacheVariable->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
+          CacheVariable->InDeletedTransitionPtr->State = State;\r
+        }\r
+      } else {\r
+        goto Done;\r
+      }\r
+    }\r
+\r
     State = Variable->CurrPtr->State;\r
     State &= VAR_DELETED;\r
 \r
@@ -1690,11 +2745,16 @@ UpdateVariable (
              sizeof (UINT8),\r
              &State\r
              );\r
+    if (!EFI_ERROR (Status) && !Variable->Volatile) {\r
+      CacheVariable->CurrPtr->State = State;\r
+    }\r
   }\r
 \r
   if (!EFI_ERROR (Status)) {\r
     UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE);\r
-    UpdateVariableCache (VariableName, VendorGuid, Attributes, DataSize, Data);\r
+    if (!Volatile) {\r
+      FlushHobVariableToFlash (VariableName, VendorGuid);\r
+    }\r
   }\r
 \r
 Done:\r
@@ -1705,27 +2765,32 @@ Done:
 \r
   This code finds variable in storage blocks (Volatile or Non-Volatile).\r
 \r
+  Caution: This function may receive untrusted input.\r
+  This function may be invoked in SMM mode, and datasize is external input.\r
+  This function will do basic validation, before parse the data.\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
+  @param Data                       The buffer to return the contents of the variable. May be NULL\r
+                                    with a zero DataSize in order to determine the size buffer needed.\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
-RuntimeServiceGetVariable (\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
+  OUT     VOID              *Data OPTIONAL\r
   )\r
 {\r
   EFI_STATUS              Status;\r
@@ -1736,19 +2801,13 @@ RuntimeServiceGetVariable (
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
+  if (VariableName[0] == 0) {\r
+    return EFI_NOT_FOUND;\r
+  }\r
+\r
   AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\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
+  Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
   if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {\r
     goto Done;\r
   }\r
@@ -1772,8 +2831,7 @@ RuntimeServiceGetVariable (
 \r
     *DataSize = VarDataSize;\r
     UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE);\r
-    UpdateVariableCache (VariableName, VendorGuid, Variable.CurrPtr->Attributes, VarDataSize, Data);\r
\r
+\r
     Status = EFI_SUCCESS;\r
     goto Done;\r
   } else {\r
@@ -1787,97 +2845,155 @@ Done:
   return Status;\r
 }\r
 \r
-\r
-\r
 /**\r
-\r
   This code Finds the Next available variable.\r
 \r
-  @param VariableNameSize           Size of the variable name\r
-  @param VariableName               Pointer to variable name\r
-  @param VendorGuid                 Variable Vendor Guid\r
+  Caution: This function may receive untrusted input.\r
+  This function may be invoked in SMM mode. This function will do basic validation, before parse the data.\r
+\r
+  @param[in]  VariableName  Pointer to variable name.\r
+  @param[in]  VendorGuid    Variable Vendor Guid.\r
+  @param[out] VariablePtr   Pointer to variable header address.\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 function completed successfully.\r
+  @retval EFI_NOT_FOUND         The next variable was not found.\r
+  @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while VendorGuid is NULL.\r
+  @retval EFI_INVALID_PARAMETER The input values of VariableName and VendorGuid are not a name and\r
+                                GUID of an existing variable.\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
+VariableServiceGetNextVariableInternal (\r
+  IN  CHAR16                *VariableName,\r
+  IN  EFI_GUID              *VendorGuid,\r
+  OUT VARIABLE_HEADER       **VariablePtr\r
   )\r
 {\r
+  VARIABLE_STORE_TYPE     Type;\r
   VARIABLE_POINTER_TRACK  Variable;\r
-  UINTN                   VarNameSize;\r
+  VARIABLE_POINTER_TRACK  VariableInHob;\r
+  VARIABLE_POINTER_TRACK  VariablePtrTrack;\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);\r
+  Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
   if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {\r
+    //\r
+    // For VariableName is an empty string, FindVariable() will try to find and return\r
+    // the first qualified variable, and if FindVariable() returns error (EFI_NOT_FOUND)\r
+    // as no any variable is found, still go to return the error (EFI_NOT_FOUND).\r
+    //\r
+    if (VariableName[0] != 0) {\r
+      //\r
+      // For VariableName is not an empty string, and FindVariable() returns error as\r
+      // VariableName and VendorGuid are not a name and GUID of an existing variable,\r
+      // there is no way to get next variable, follow spec to return EFI_INVALID_PARAMETER.\r
+      //\r
+      Status = EFI_INVALID_PARAMETER;\r
+    }\r
     goto Done;\r
   }\r
 \r
   if (VariableName[0] != 0) {\r
     //\r
-    // If variable name is not NULL, get next variable\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
-    // If both volatile and non-volatile variable store are parsed,\r
-    // return not found\r
+    // Switch from Volatile to HOB, to Non-Volatile.\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
-      } else {\r
+    while (!IsValidVariableHeader (Variable.CurrPtr, Variable.EndPtr)) {\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
-\r
-      Variable.CurrPtr = Variable.StartPtr;\r
-      if (!IsValidVariableHeader (Variable.CurrPtr)) {\r
-        continue;\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 (IsValidVariableHeader (Variable.CurrPtr) && Variable.CurrPtr->State == VAR_ADDED) {\r
-      if ((EfiAtRuntime () && ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) == 0) {\r
-        VarNameSize = NameSizeOfVariable (Variable.CurrPtr);\r
-        ASSERT (VarNameSize != 0);\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
+                     GetVendorGuidPtr (Variable.CurrPtr),\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
-        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
-        } else {\r
-          Status = EFI_BUFFER_TOO_SMALL;\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
+                     GetVendorGuidPtr (Variable.CurrPtr),\r
+                     FALSE,\r
+                     &VariableInHob\r
+                     );\r
+          if (!EFI_ERROR (Status)) {\r
+            Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);\r
+            continue;\r
+          }\r
         }\r
 \r
-        *VariableNameSize = VarNameSize;\r
+        *VariablePtr = Variable.CurrPtr;\r
+        Status = EFI_SUCCESS;\r
         goto Done;\r
       }\r
     }\r
@@ -1886,6 +3002,80 @@ RuntimeServiceGetNextVariableName (
   }\r
 \r
 Done:\r
+  return Status;\r
+}\r
+\r
+/**\r
+\r
+  This code Finds the Next available variable.\r
+\r
+  Caution: This function may receive untrusted input.\r
+  This function may be invoked in SMM mode. This function will do basic validation, before parse the data.\r
+\r
+  @param VariableNameSize           The size of the VariableName buffer. The size must be large\r
+                                    enough to fit input string supplied in VariableName buffer.\r
+  @param VariableName               Pointer to variable name.\r
+  @param VendorGuid                 Variable Vendor Guid.\r
+\r
+  @retval EFI_SUCCESS               The function completed successfully.\r
+  @retval EFI_NOT_FOUND             The next variable was not found.\r
+  @retval EFI_BUFFER_TOO_SMALL      The VariableNameSize is too small for the result.\r
+                                    VariableNameSize has been updated with the size needed to complete the request.\r
+  @retval EFI_INVALID_PARAMETER     VariableNameSize is NULL.\r
+  @retval EFI_INVALID_PARAMETER     VariableName is NULL.\r
+  @retval EFI_INVALID_PARAMETER     VendorGuid is NULL.\r
+  @retval EFI_INVALID_PARAMETER     The input values of VariableName and VendorGuid are not a name and\r
+                                    GUID of an existing variable.\r
+  @retval EFI_INVALID_PARAMETER     Null-terminator is not found in the first VariableNameSize bytes of\r
+                                    the input VariableName buffer.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+VariableServiceGetNextVariableName (\r
+  IN OUT  UINTN             *VariableNameSize,\r
+  IN OUT  CHAR16            *VariableName,\r
+  IN OUT  EFI_GUID          *VendorGuid\r
+  )\r
+{\r
+  EFI_STATUS              Status;\r
+  UINTN                   MaxLen;\r
+  UINTN                   VarNameSize;\r
+  VARIABLE_HEADER         *VariablePtr;\r
+\r
+  if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  // Calculate the possible maximum length of name string, including the Null terminator.\r
+  //\r
+  MaxLen = *VariableNameSize / sizeof (CHAR16);\r
+  if ((MaxLen == 0) || (StrnLenS (VariableName, MaxLen) == MaxLen)) {\r
+    //\r
+    // Null-terminator is not found in the first VariableNameSize bytes of the input VariableName buffer,\r
+    // follow spec to return EFI_INVALID_PARAMETER.\r
+    //\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
+\r
+  Status = VariableServiceGetNextVariableInternal (VariableName, VendorGuid, &VariablePtr);\r
+  if (!EFI_ERROR (Status)) {\r
+    VarNameSize = NameSizeOfVariable (VariablePtr);\r
+    ASSERT (VarNameSize != 0);\r
+    if (VarNameSize <= *VariableNameSize) {\r
+      CopyMem (VariableName, GetVariableNamePtr (VariablePtr), VarNameSize);\r
+      CopyMem (VendorGuid, GetVendorGuidPtr (VariablePtr), sizeof (EFI_GUID));\r
+      Status = EFI_SUCCESS;\r
+    } else {\r
+      Status = EFI_BUFFER_TOO_SMALL;\r
+    }\r
+\r
+    *VariableNameSize = VarNameSize;\r
+  }\r
+\r
   ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
   return Status;\r
 }\r
@@ -1894,23 +3084,30 @@ Done:
 \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
+  Caution: This function may receive untrusted input.\r
+  This function may be invoked in SMM mode, and datasize and data are external input.\r
+  This function will do basic validation, before parse the data.\r
+  This function will parse the authentication carefully to avoid security issues, like\r
+  buffer overflow, integer overflow.\r
+  This function will check attribute carefully to avoid authentication bypass.\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
+  @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
+  @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
-RuntimeServiceSetVariable (\r
+VariableServiceSetVariable (\r
   IN CHAR16                  *VariableName,\r
   IN EFI_GUID                *VendorGuid,\r
   IN UINT32                  Attributes,\r
@@ -1922,9 +3119,10 @@ RuntimeServiceSetVariable (
   EFI_STATUS                          Status;\r
   VARIABLE_HEADER                     *NextVariable;\r
   EFI_PHYSICAL_ADDRESS                Point;\r
+  UINTN                               PayloadSize;\r
 \r
   //\r
-  // Check input parameters\r
+  // Check input parameters.\r
   //\r
   if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {\r
     return EFI_INVALID_PARAMETER;\r
@@ -1935,72 +3133,195 @@ RuntimeServiceSetVariable (
   }\r
 \r
   //\r
-  //  Make sure if runtime bit is set, boot service bit is set also\r
+  // Check for reserverd bit in variable attribute.\r
+  // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS is deprecated but we still allow\r
+  // the delete operation of common authenticated variable at user physical presence.\r
+  // So leave EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS attribute check to AuthVariableLib\r
   //\r
-  if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {\r
+  if ((Attributes & (~(EFI_VARIABLE_ATTRIBUTES_MASK | EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS))) != 0) {\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 FixedPcdGet32(PcdMaxHardwareErrorVariableSize)\r
-  //  bytes for HwErrRec, and FixedPcdGet32(PcdMaxVariableSize) bytes for the others.\r
+  //  Make sure if runtime bit is set, boot service bit is set also.\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
+  if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {\r
+    if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0) {\r
+      return EFI_UNSUPPORTED;\r
+    } else {\r
       return EFI_INVALID_PARAMETER;\r
     }\r
-    //\r
-    // According to UEFI spec, HARDWARE_ERROR_RECORD variable name convention should be L"HwErrRecXXXX"\r
-    //\r
-    if (StrnCmp(VariableName, L"HwErrRec", StrLen(L"HwErrRec")) != 0) {\r
+  } else if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {\r
+    if (!mVariableModuleGlobal->VariableGlobal.AuthSupport) {\r
+      //\r
+      // Not support authenticated variable write.\r
+      //\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 FixedPcdGet32(PcdMaxVariableSize) bytes.\r
-    //\r
-    if ((DataSize > FixedPcdGet32(PcdMaxVariableSize)) ||\r
-        (sizeof (VARIABLE_HEADER) + StrSize (VariableName) + DataSize > FixedPcdGet32(PcdMaxVariableSize))) {\r
+  } else if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) {\r
+    if (PcdGet32 (PcdHwErrStorageSize) == 0) {\r
+      //\r
+      // Not support harware error record variable variable.\r
+      //\r
       return EFI_INVALID_PARAMETER;\r
-    }  \r
-  }  \r
-\r
-  AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
+    }\r
+  }\r
 \r
   //\r
-  // Consider reentrant in MCA/INIT/NMI. It needs be reupdated;\r
+  // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS and EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute\r
+  // cannot be set both.\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
+  if (((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS)\r
+     && ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) {\r
+    return EFI_UNSUPPORTED;\r
+  }\r
+\r
+  if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) {\r
+    //\r
+    //  If DataSize == AUTHINFO_SIZE and then PayloadSize is 0.\r
+    //  Maybe it's the delete operation of common authenticated variable at user physical presence.\r
+    //\r
+    if (DataSize != AUTHINFO_SIZE) {\r
+      return EFI_UNSUPPORTED;\r
+    }\r
+    PayloadSize = DataSize - AUTHINFO_SIZE;\r
+  } else if ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) {\r
+    //\r
+    // Sanity check for EFI_VARIABLE_AUTHENTICATION_2 descriptor.\r
+    //\r
+    if (DataSize < OFFSET_OF_AUTHINFO2_CERT_DATA ||\r
+      ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength > DataSize - (OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo)) ||\r
+      ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength < OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData)) {\r
+      return EFI_SECURITY_VIOLATION;\r
+    }\r
+    PayloadSize = DataSize - AUTHINFO2_SIZE (Data);\r
+  } else {\r
+    PayloadSize = DataSize;\r
+  }\r
+\r
+  if ((UINTN)(~0) - PayloadSize < 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#### variable.\r
+  //\r
+  if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+    if (StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxHardwareErrorVariableSize) - GetVariableHeaderSize ()) {\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 Max(Auth)VariableSize bytes.\r
+    //\r
+    if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {\r
+      if (StrSize (VariableName) + PayloadSize > mVariableModuleGlobal->MaxAuthVariableSize - GetVariableHeaderSize ()) {\r
+        return EFI_INVALID_PARAMETER;\r
+      }\r
+    } else {\r
+      if (StrSize (VariableName) + PayloadSize > mVariableModuleGlobal->MaxVariableSize - GetVariableHeaderSize ()) {\r
+        return EFI_INVALID_PARAMETER;\r
+      }\r
+    }\r
+  }\r
+\r
+  //\r
+  // Special Handling for MOR Lock variable.\r
+  //\r
+  Status = SetVariableCheckHandlerMor (VariableName, VendorGuid, Attributes, PayloadSize, (VOID *) ((UINTN) Data + DataSize - PayloadSize));\r
+  if (Status == EFI_ALREADY_STARTED) {\r
+    //\r
+    // EFI_ALREADY_STARTED means the SetVariable() action is handled inside of SetVariableCheckHandlerMor().\r
+    // Variable driver can just return SUCCESS.\r
+    //\r
+    return EFI_SUCCESS;\r
+  }\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+\r
+  Status = VarCheckLibSetVariableCheck (VariableName, VendorGuid, Attributes, PayloadSize, (VOID *) ((UINTN) Data + DataSize - PayloadSize), mRequestSource);\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
+    while (IsValidVariableHeader (NextVariable, GetEndPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point))) {\r
       NextVariable = GetNextVariablePtr (NextVariable);\r
     }\r
     mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) Point;\r
   }\r
 \r
   //\r
-  // Check whether the input variable is already existed\r
+  // Check whether the input variable is already existed.\r
   //\r
-  FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal);\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 & (~EFI_VARIABLE_APPEND_WRITE)) != 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
+      DEBUG ((EFI_D_INFO, "[Variable]: Rewritten a preexisting variable(0x%08x) with different attributes(0x%08x) - %g:%s\n", Variable.CurrPtr->Attributes, Attributes, VendorGuid, VariableName));\r
+      goto Done;\r
+    }\r
+  }\r
 \r
-  //\r
-  // Hook the operation of setting PlatformLangCodes/PlatformLang and LangCodes/Lang\r
-  //\r
-  AutoUpdateLangVariable (VariableName, Data, DataSize);\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
+  if (mVariableModuleGlobal->VariableGlobal.AuthSupport) {\r
+    Status = AuthVariableLibProcessVariable (VariableName, VendorGuid, Data, DataSize, Attributes);\r
+  } else {\r
+    Status = UpdateVariable (VariableName, VendorGuid, Data, DataSize, Attributes, 0, 0, &Variable, NULL);\r
+  }\r
 \r
+Done:\r
   InterlockedDecrement (&mVariableModuleGlobal->VariableGlobal.ReentrantState);\r
   ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
 \r
+  if (!AtRuntime ()) {\r
+    if (!EFI_ERROR (Status)) {\r
+      SecureBootHook (\r
+        VariableName,\r
+        VendorGuid\r
+        );\r
+    }\r
+  }\r
+\r
   return Status;\r
 }\r
 \r
@@ -2008,6 +3329,9 @@ RuntimeServiceSetVariable (
 \r
   This code returns information about the EFI variables.\r
 \r
+  Caution: This function may receive untrusted input.\r
+  This function may be invoked in SMM mode. This function will do basic validation, before parse the data.\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
@@ -2017,14 +3341,12 @@ RuntimeServiceSetVariable (
   @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
-RuntimeServiceQueryVariableInfo (\r
+VariableServiceQueryVariableInfoInternal (\r
   IN  UINT32                 Attributes,\r
   OUT UINT64                 *MaximumVariableStorageSize,\r
   OUT UINT64                 *RemainingVariableStorageSize,\r
@@ -2037,25 +3359,193 @@ RuntimeServiceQueryVariableInfo (
   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) - GetVariableHeaderSize ();\r
+  } else {\r
+    if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {\r
+      if (AtRuntime ()) {\r
+        *MaximumVariableStorageSize = mVariableModuleGlobal->CommonRuntimeVariableSpace;\r
+      } else {\r
+        *MaximumVariableStorageSize = mVariableModuleGlobal->CommonVariableSpace;\r
+      }\r
+    }\r
+\r
+    //\r
+    // Let *MaximumVariableSize be Max(Auth)VariableSize with the exception of the variable header size.\r
+    //\r
+    if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {\r
+      *MaximumVariableSize = mVariableModuleGlobal->MaxAuthVariableSize - GetVariableHeaderSize ();\r
+    } else {\r
+      *MaximumVariableSize = mVariableModuleGlobal->MaxVariableSize - GetVariableHeaderSize ();\r
+    }\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 (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {\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
+                   GetVendorGuidPtr (Variable),\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
+    if (*MaximumVariableStorageSize < CommonVariableTotalSize) {\r
+      *RemainingVariableStorageSize = 0;\r
+    } else {\r
+      *RemainingVariableStorageSize = *MaximumVariableStorageSize - CommonVariableTotalSize;\r
+    }\r
+  }\r
+\r
+  if (*RemainingVariableStorageSize < GetVariableHeaderSize ()) {\r
+    *MaximumVariableSize = 0;\r
+  } else if ((*RemainingVariableStorageSize - GetVariableHeaderSize ()) < *MaximumVariableSize) {\r
+    *MaximumVariableSize = *RemainingVariableStorageSize - GetVariableHeaderSize ();\r
+  }\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+/**\r
+\r
+  This code returns information about the EFI variables.\r
+\r
+  Caution: This function may receive untrusted input.\r
+  This function may be invoked in SMM mode. This function will do basic validation, before parse the data.\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
+  if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0) {\r
+    //\r
+    //  Deprecated attribute, make this check as highest priority.\r
+    //\r
+    return EFI_UNSUPPORTED;\r
+  }\r
+\r
+  if ((Attributes & EFI_VARIABLE_ATTRIBUTES_MASK) == 0) {\r
     //\r
     // Make sure the Attributes combination is supported by the platform.\r
     //\r
-    return EFI_UNSUPPORTED;  \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
+  } 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
@@ -2065,183 +3555,608 @@ RuntimeServiceQueryVariableInfo (
     // Make sure Hw Attribute is set with NV.\r
     //\r
     return EFI_INVALID_PARAMETER;\r
+  } else if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {\r
+    if (!mVariableModuleGlobal->VariableGlobal.AuthSupport) {\r
+      //\r
+      // Not support authenticated variable write.\r
+      //\r
+      return EFI_UNSUPPORTED;\r
+    }\r
+  } else if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) {\r
+    if (PcdGet32 (PcdHwErrStorageSize) == 0) {\r
+      //\r
+      // Not support harware error record variable variable.\r
+      //\r
+      return EFI_UNSUPPORTED;\r
+    }\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
+  Caution: This function may be invoked at SMM mode.\r
+  Care must be taken to make sure not security issue.\r
+\r
+**/\r
+VOID\r
+ReclaimForOS(\r
+  VOID\r
+  )\r
+{\r
+  EFI_STATUS                     Status;\r
+  UINTN                          RemainingCommonRuntimeVariableSpace;\r
+  UINTN                          RemainingHwErrVariableSpace;\r
+  STATIC BOOLEAN                 Reclaimed;\r
+\r
+  //\r
+  // This function will be called only once at EndOfDxe or ReadyToBoot event.\r
+  //\r
+  if (Reclaimed) {\r
+    return;\r
+  }\r
+  Reclaimed = TRUE;\r
+\r
+  Status  = EFI_SUCCESS;\r
+\r
+  if (mVariableModuleGlobal->CommonRuntimeVariableSpace < mVariableModuleGlobal->CommonVariableTotalSize) {\r
+    RemainingCommonRuntimeVariableSpace = 0;\r
+  } else {\r
+    RemainingCommonRuntimeVariableSpace = mVariableModuleGlobal->CommonRuntimeVariableSpace - mVariableModuleGlobal->CommonVariableTotalSize;\r
+  }\r
+\r
+  RemainingHwErrVariableSpace = PcdGet32 (PcdHwErrStorageSize) - mVariableModuleGlobal->HwErrVariableTotalSize;\r
+\r
+  //\r
+  // Check if the free area is below a threshold.\r
+  //\r
+  if (((RemainingCommonRuntimeVariableSpace < mVariableModuleGlobal->MaxVariableSize) ||\r
+       (RemainingCommonRuntimeVariableSpace < mVariableModuleGlobal->MaxAuthVariableSize)) ||\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
+  Get non-volatile maximum variable size.\r
+\r
+  @return Non-volatile maximum variable size.\r
+\r
+**/\r
+UINTN\r
+GetNonVolatileMaxVariableSize (\r
+  VOID\r
+  )\r
+{\r
+  if (PcdGet32 (PcdHwErrStorageSize) != 0) {\r
+    return MAX (MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxAuthVariableSize)),\r
+                PcdGet32 (PcdMaxHardwareErrorVariableSize));\r
+  } else {\r
+    return MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxAuthVariableSize));\r
+  }\r
+}\r
+\r
+/**\r
+  Init non-volatile variable store.\r
+\r
+  @param[out] NvFvHeader        Output pointer to non-volatile FV header address.\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
+  OUT EFI_FIRMWARE_VOLUME_HEADER    **NvFvHeader\r
+  )\r
+{\r
+  EFI_FIRMWARE_VOLUME_HEADER            *FvHeader;\r
+  VARIABLE_HEADER                       *Variable;\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
+  UINT32                                HwErrStorageSize;\r
+  UINT32                                MaxUserNvVariableSpaceSize;\r
+  UINT32                                BoottimeReservedNvVariableSpaceSize;\r
+  EFI_STATUS                            Status;\r
+  VOID                                  *FtwProtocol;\r
+\r
+  mVariableModuleGlobal->FvbInstance = NULL;\r
+\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
+  // Copy NV storage data to the memory buffer.\r
+  //\r
+  CopyMem (NvStorageData, (UINT8 *) (UINTN) NvStorageBase, NvStorageSize);\r
+\r
+  Status = GetFtwProtocol ((VOID **)&FtwProtocol);\r
+  //\r
+  // If FTW protocol has been installed, no need to check FTW last write data hob.\r
+  //\r
+  if (EFI_ERROR (Status)) {\r
+    //\r
+    // Check the FTW last write data hob.\r
+    //\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
+\r
+  FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *) NvStorageData;\r
+\r
+  //\r
+  // Check if the Firmware Volume is not corrupted\r
+  //\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 = (UINTN) FvHeader + FvHeader->HeaderLength;\r
+  VariableStoreLength = NvStorageSize - FvHeader->HeaderLength;\r
+\r
+  mNvFvHeaderCache = FvHeader;\r
+  mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;\r
+  mNvVariableCache = (VARIABLE_STORE_HEADER *) (UINTN) VariableStoreBase;\r
+  if (GetVariableStoreStatus (mNvVariableCache) != EfiValid) {\r
+    FreePool (NvStorageData);\r
+    mNvFvHeaderCache = NULL;\r
+    mNvVariableCache = NULL;\r
+    DEBUG((EFI_D_ERROR, "Variable Store header is corrupted\n"));\r
+    return EFI_VOLUME_CORRUPTED;\r
+  }\r
+  ASSERT(mNvVariableCache->Size == VariableStoreLength);\r
+\r
+  ASSERT (sizeof (VARIABLE_STORE_HEADER) <= VariableStoreLength);\r
+\r
+  mVariableModuleGlobal->VariableGlobal.AuthFormat = (BOOLEAN)(CompareGuid (&mNvVariableCache->Signature, &gEfiAuthenticatedVariableGuid));\r
+\r
+  HwErrStorageSize = PcdGet32 (PcdHwErrStorageSize);\r
+  MaxUserNvVariableSpaceSize = PcdGet32 (PcdMaxUserNvVariableSpaceSize);\r
+  BoottimeReservedNvVariableSpaceSize = PcdGet32 (PcdBoottimeReservedNvVariableSpaceSize);\r
+\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 the value of\r
+  // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)).\r
+  //\r
+  ASSERT (HwErrStorageSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)));\r
+  //\r
+  // Ensure that the value of PcdMaxUserNvVariableSpaceSize is less than the value of\r
+  // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize).\r
+  //\r
+  ASSERT (MaxUserNvVariableSpaceSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize));\r
+  //\r
+  // Ensure that the value of PcdBoottimeReservedNvVariableSpaceSize is less than the value of\r
+  // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize).\r
+  //\r
+  ASSERT (BoottimeReservedNvVariableSpaceSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize));\r
+\r
+  mVariableModuleGlobal->CommonVariableSpace = ((UINTN) VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize);\r
+  mVariableModuleGlobal->CommonMaxUserVariableSpace = ((MaxUserNvVariableSpaceSize != 0) ? MaxUserNvVariableSpaceSize : mVariableModuleGlobal->CommonVariableSpace);\r
+  mVariableModuleGlobal->CommonRuntimeVariableSpace = mVariableModuleGlobal->CommonVariableSpace - BoottimeReservedNvVariableSpaceSize;\r
+\r
+  DEBUG ((EFI_D_INFO, "Variable driver common space: 0x%x 0x%x 0x%x\n", mVariableModuleGlobal->CommonVariableSpace, mVariableModuleGlobal->CommonMaxUserVariableSpace, mVariableModuleGlobal->CommonRuntimeVariableSpace));\r
+\r
+  //\r
+  // The max NV variable size should be < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)).\r
+  //\r
+  ASSERT (GetNonVolatileMaxVariableSize () < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)));\r
+\r
+  mVariableModuleGlobal->MaxVariableSize = PcdGet32 (PcdMaxVariableSize);\r
+  mVariableModuleGlobal->MaxAuthVariableSize = ((PcdGet32 (PcdMaxAuthVariableSize) != 0) ? PcdGet32 (PcdMaxAuthVariableSize) : mVariableModuleGlobal->MaxVariableSize);\r
+\r
+  //\r
+  // Parse non-volatile variable data and get last variable offset.\r
+  //\r
+  Variable  = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase);\r
+  while (IsValidVariableHeader (Variable, GetEndPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase))) {\r
+    NextVariable = GetNextVariablePtr (Variable);\r
+    VariableSize = (UINTN) NextVariable - (UINTN) Variable;\r
+    if ((Variable->Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {\r
+      mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize;\r
+    } else {\r
+      mVariableModuleGlobal->CommonVariableTotalSize += VariableSize;\r
+    }\r
+\r
+    Variable = NextVariable;\r
+  }\r
+  mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) Variable - (UINTN) VariableStoreBase;\r
+\r
+  *NvFvHeader = FvHeader;\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
+  VARIABLE_POINTER_TRACK        VariablePtrTrack;\r
+  BOOLEAN                       ErrorFlag;\r
+\r
+  ErrorFlag = FALSE;\r
+\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
+        ; IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))\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, GetVendorGuidPtr (Variable)) ||\r
+          StrCmp (VariableName, GetVariableNamePtr (Variable)) != 0) {\r
+        VariableData = GetVariableDataPtr (Variable);\r
+        FindVariable (GetVariableNamePtr (Variable), GetVendorGuidPtr (Variable), &VariablePtrTrack, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
+        Status = UpdateVariable (\r
+                   GetVariableNamePtr (Variable),\r
+                   GetVendorGuidPtr (Variable),\r
+                   VariableData,\r
+                   DataSizeOfVariable (Variable),\r
+                   Variable->Attributes,\r
+                   0,\r
+                   0,\r
+                   &VariablePtrTrack,\r
+                   NULL\r
+                 );\r
+        DEBUG ((EFI_D_INFO, "Variable driver flush the HOB variable to flash: %g %s %r\n", GetVendorGuidPtr (Variable), GetVariableNamePtr (Variable), Status));\r
+      } else {\r
+        //\r
+        // The updated or deleted variable is matched with this 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", GetVendorGuidPtr (Variable), GetVariableNamePtr (Variable)));\r
+        Variable->State &= VAR_DELETED;\r
+      } else {\r
+        ErrorFlag = TRUE;\r
+      }\r
+    }\r
+    if (ErrorFlag) {\r
+      //\r
+      // We still have HOB variable(s) not flushed in flash.\r
+      //\r
+      mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStoreHeader;\r
+    } else {\r
+      //\r
+      // All HOB variables have been flushed in flash.\r
+      //\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
-  AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
+}\r
+\r
+/**\r
+  Initializes variable write service after FTW was ready.\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
+  @retval EFI_SUCCESS          Function successfully executed.\r
+  @retval Others               Fail to initialize the variable service.\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
+EFI_STATUS\r
+VariableWriteServiceInitialize (\r
+  VOID\r
+  )\r
+{\r
+  EFI_STATUS                      Status;\r
+  UINTN                           Index;\r
+  UINT8                           Data;\r
+  EFI_PHYSICAL_ADDRESS            VariableStoreBase;\r
+  EFI_PHYSICAL_ADDRESS            NvStorageBase;\r
+  VARIABLE_ENTRY_PROPERTY         *VariableEntry;\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 = FixedPcdGet32(PcdHwErrStorageSize);\r
-    *MaximumVariableSize = FixedPcdGet32(PcdMaxHardwareErrorVariableSize) - sizeof (VARIABLE_HEADER);\r
-  } else {\r
-    if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {\r
-      ASSERT (FixedPcdGet32(PcdHwErrStorageSize) < VariableStoreHeader->Size);\r
-      *MaximumVariableStorageSize = VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER) - FixedPcdGet32(PcdHwErrStorageSize);\r
-    }\r
+  AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
 \r
-    //\r
-    // Let *MaximumVariableSize be FixedPcdGet32(PcdMaxVariableSize) with the exception of the variable header size.\r
-    //\r
-    *MaximumVariableSize = FixedPcdGet32(PcdMaxVariableSize) - sizeof (VARIABLE_HEADER);\r
+  NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageVariableBase64);\r
+  if (NvStorageBase == 0) {\r
+    NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageVariableBase);\r
   }\r
+  VariableStoreBase = NvStorageBase + (mNvFvHeaderCache->HeaderLength);\r
 \r
   //\r
-  // Point to the starting address of the variables.\r
+  // Let NonVolatileVariableBase point to flash variable store base directly after FTW ready.\r
   //\r
-  Variable = GetStartPointer (VariableStoreHeader);\r
+  mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;\r
 \r
   //\r
-  // Now walk through the related variable store.\r
+  // Check if the free area is really free.\r
   //\r
-  while ((Variable < GetEndPointer (VariableStoreHeader)) && IsValidVariableHeader (Variable)) {\r
-    NextVariable = GetNextVariablePtr (Variable);\r
-    VariableSize = (UINT64) (UINTN) NextVariable - (UINT64) (UINTN) Variable;\r
-\r
-    if (EfiAtRuntime ()) {\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 ((NextVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
-        HwErrVariableTotalSize += VariableSize;\r
-      } else {\r
-        CommonVariableTotalSize += VariableSize;\r
-      }\r
-    } else {\r
+  for (Index = mVariableModuleGlobal->NonVolatileLastVariableOffset; Index < mNvVariableCache->Size; Index++) {\r
+    Data = ((UINT8 *) mNvVariableCache)[Index];\r
+    if (Data != 0xff) {\r
       //\r
-      // Only care about Variables with State VAR_ADDED,because\r
-      // the space not marked as VAR_ADDED is reclaimable now.\r
+      // There must be something wrong in variable store, do reclaim operation.\r
       //\r
-      if (Variable->State == VAR_ADDED) {\r
-        if ((NextVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
-          HwErrVariableTotalSize += VariableSize;\r
-        } else {\r
-          CommonVariableTotalSize += VariableSize;\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
+        ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
+        return Status;\r
       }\r
+      break;\r
     }\r
+  }\r
+\r
+  FlushHobVariableToFlash (NULL, NULL);\r
 \r
+  Status = EFI_SUCCESS;\r
+  ZeroMem (&mAuthContextOut, sizeof (mAuthContextOut));\r
+  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {\r
     //\r
-    // Go to the next one\r
+    // Authenticated variable initialize.\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
+    mAuthContextIn.StructSize = sizeof (AUTH_VAR_LIB_CONTEXT_IN);\r
+    mAuthContextIn.MaxAuthVariableSize = mVariableModuleGlobal->MaxAuthVariableSize - GetVariableHeaderSize ();\r
+    Status = AuthVariableLibInitialize (&mAuthContextIn, &mAuthContextOut);\r
+    if (!EFI_ERROR (Status)) {\r
+      DEBUG ((EFI_D_INFO, "Variable driver will work with auth variable support!\n"));\r
+      mVariableModuleGlobal->VariableGlobal.AuthSupport = TRUE;\r
+      if (mAuthContextOut.AuthVarEntry != NULL) {\r
+        for (Index = 0; Index < mAuthContextOut.AuthVarEntryCount; Index++) {\r
+          VariableEntry = &mAuthContextOut.AuthVarEntry[Index];\r
+          Status = VarCheckLibVariablePropertySet (\r
+                     VariableEntry->Name,\r
+                     VariableEntry->Guid,\r
+                     &VariableEntry->VariableProperty\r
+                     );\r
+          ASSERT_EFI_ERROR (Status);\r
+        }\r
+      }\r
+    } else if (Status == EFI_UNSUPPORTED) {\r
+      DEBUG ((EFI_D_INFO, "NOTICE - AuthVariableLibInitialize() returns %r!\n", Status));\r
+      DEBUG ((EFI_D_INFO, "Variable driver will continue to work without auth variable support!\n"));\r
+      mVariableModuleGlobal->VariableGlobal.AuthSupport = FALSE;\r
+      Status = EFI_SUCCESS;\r
+    }\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
+  if (!EFI_ERROR (Status)) {\r
+    for (Index = 0; Index < ARRAY_SIZE (mVariableEntryProperty); Index++) {\r
+      VariableEntry = &mVariableEntryProperty[Index];\r
+      Status = VarCheckLibVariablePropertySet (VariableEntry->Name, VariableEntry->Guid, &VariableEntry->VariableProperty);\r
+      ASSERT_EFI_ERROR (Status);\r
+    }\r
   }\r
 \r
   ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
-  return EFI_SUCCESS;\r
-}\r
 \r
+  //\r
+  // Initialize MOR Lock variable.\r
+  //\r
+  MorLockInit ();\r
+\r
+  return Status;\r
+}\r
 \r
 /**\r
-  Notification function of EVT_GROUP_READY_TO_BOOT event group.\r
+  Convert normal variable storage to the allocated auth variable storage.\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
+  @param[in]  NormalVarStorage  Pointer to the normal variable storage header\r
 \r
+  @retval the allocated auth variable storage\r
 **/\r
-VOID\r
-EFIAPI\r
-ReclaimForOS(\r
-  EFI_EVENT  Event,\r
-  VOID       *Context\r
+VOID *\r
+ConvertNormalVarStorageToAuthVarStorage (\r
+  VARIABLE_STORE_HEADER *NormalVarStorage\r
   )\r
 {\r
-  EFI_STATUS                     Status;\r
-  UINTN                          CommonVariableSpace;\r
-  UINTN                          RemainingCommonVariableSpace;\r
-  UINTN                          RemainingHwErrVariableSpace;\r
-\r
-  Status  = EFI_SUCCESS; \r
+  VARIABLE_HEADER *StartPtr;\r
+  UINT8           *NextPtr;\r
+  VARIABLE_HEADER *EndPtr;\r
+  UINTN           AuthVarStroageSize;\r
+  AUTHENTICATED_VARIABLE_HEADER *AuthStartPtr;\r
+  VARIABLE_STORE_HEADER         *AuthVarStorage;\r
+\r
+  AuthVarStroageSize  = sizeof (VARIABLE_STORE_HEADER);\r
+  //\r
+  // Set AuthFormat as FALSE for normal variable storage\r
+  //\r
+  mVariableModuleGlobal->VariableGlobal.AuthFormat = FALSE;\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
+  // Calculate Auth Variable Storage Size\r
+  //\r
+  StartPtr = GetStartPointer (NormalVarStorage);\r
+  EndPtr   = GetEndPointer (NormalVarStorage);\r
+  while (StartPtr < EndPtr) {\r
+    if (StartPtr->State == VAR_ADDED) {\r
+      AuthVarStroageSize = HEADER_ALIGN (AuthVarStroageSize);\r
+      AuthVarStroageSize += sizeof (AUTHENTICATED_VARIABLE_HEADER);\r
+      AuthVarStroageSize += StartPtr->NameSize + GET_PAD_SIZE (StartPtr->NameSize);\r
+      AuthVarStroageSize += StartPtr->DataSize + GET_PAD_SIZE (StartPtr->DataSize);\r
+    }\r
+    StartPtr  = GetNextVariablePtr (StartPtr);\r
+  }\r
 \r
-  RemainingCommonVariableSpace = CommonVariableSpace - mVariableModuleGlobal->CommonVariableTotalSize;\r
+  //\r
+  // Allocate Runtime memory for Auth Variable Storage\r
+  //\r
+  AuthVarStorage = AllocateRuntimeZeroPool (AuthVarStroageSize);\r
+  ASSERT (AuthVarStorage != NULL);\r
+  if (AuthVarStorage == NULL) {\r
+    return NULL;\r
+  }\r
 \r
-  RemainingHwErrVariableSpace = PcdGet32 (PcdHwErrStorageSize) - mVariableModuleGlobal->HwErrVariableTotalSize;\r
   //\r
-  // Check if the free area is blow a threshold.\r
+  // Copy Variable from Normal storage to Auth storage\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
-            );\r
-    ASSERT_EFI_ERROR (Status);\r
+  StartPtr = GetStartPointer (NormalVarStorage);\r
+  EndPtr   = GetEndPointer (NormalVarStorage);\r
+  AuthStartPtr = (AUTHENTICATED_VARIABLE_HEADER *) GetStartPointer (AuthVarStorage);\r
+  while (StartPtr < EndPtr) {\r
+    if (StartPtr->State == VAR_ADDED) {\r
+      AuthStartPtr = (AUTHENTICATED_VARIABLE_HEADER *) HEADER_ALIGN (AuthStartPtr);\r
+      //\r
+      // Copy Variable Header\r
+      //\r
+      AuthStartPtr->StartId     = StartPtr->StartId;\r
+      AuthStartPtr->State       = StartPtr->State;\r
+      AuthStartPtr->Attributes  = StartPtr->Attributes;\r
+      AuthStartPtr->NameSize    = StartPtr->NameSize;\r
+      AuthStartPtr->DataSize    = StartPtr->DataSize;\r
+      CopyGuid (&AuthStartPtr->VendorGuid, &StartPtr->VendorGuid);\r
+      //\r
+      // Copy Variable Name\r
+      //\r
+      NextPtr = (UINT8 *) (AuthStartPtr + 1);\r
+      CopyMem (NextPtr, GetVariableNamePtr (StartPtr), AuthStartPtr->NameSize);\r
+      //\r
+      // Copy Variable Data\r
+      //\r
+      NextPtr = NextPtr + AuthStartPtr->NameSize + GET_PAD_SIZE (AuthStartPtr->NameSize);\r
+      CopyMem (NextPtr, GetVariableDataPtr (StartPtr), AuthStartPtr->DataSize);\r
+      //\r
+      // Go to next variable\r
+      //\r
+      AuthStartPtr = (AUTHENTICATED_VARIABLE_HEADER *) (NextPtr + AuthStartPtr->DataSize + GET_PAD_SIZE (AuthStartPtr->DataSize));\r
+    }\r
+    StartPtr = GetNextVariablePtr (StartPtr);\r
   }\r
-}\r
+  //\r
+  // Update Auth Storage Header\r
+  //\r
+  AuthVarStorage->Format = NormalVarStorage->Format;\r
+  AuthVarStorage->State  = NormalVarStorage->State;\r
+  AuthVarStorage->Size = (UINT32) (UINTN) ((UINT8 *) AuthStartPtr - (UINT8 *) AuthVarStorage);\r
+  CopyGuid (&AuthVarStorage->Signature, &gEfiAuthenticatedVariableGuid);\r
+  ASSERT (AuthVarStorage->Size <= AuthVarStroageSize);\r
 \r
+  //\r
+  // Restore AuthFormat\r
+  //\r
+  mVariableModuleGlobal->VariableGlobal.AuthFormat = TRUE;\r
+  return AuthVarStorage;\r
+}\r
 /**\r
   Initializes variable store area for non-volatile and volatile variable.\r
 \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_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol\r
+  VOID\r
   )\r
 {\r
   EFI_STATUS                      Status;\r
   VARIABLE_STORE_HEADER           *VolatileVariableStore;\r
   VARIABLE_STORE_HEADER           *VariableStoreHeader;\r
-  VARIABLE_HEADER                 *NextVariable;\r
-  EFI_PHYSICAL_ADDRESS            TempVariableStoreHeader;\r
-  EFI_GCD_MEMORY_SPACE_DESCRIPTOR GcdDescriptor;\r
-  EFI_PHYSICAL_ADDRESS            BaseAddress;\r
-  UINT64                          Length;\r
-  UINTN                           Index;\r
-  UINT8                           Data;\r
-  EFI_PHYSICAL_ADDRESS            VariableStoreBase;\r
   UINT64                          VariableStoreLength;\r
-  EFI_EVENT                       ReadyToBootEvent;\r
   UINTN                           ScratchSize;\r
+  EFI_HOB_GUID_TYPE               *GuidHob;\r
+  EFI_GUID                        *VariableGuid;\r
+  EFI_FIRMWARE_VOLUME_HEADER      *NvFvHeader;\r
+  BOOLEAN                         IsNormalVariableHob;\r
 \r
-  Status = EFI_SUCCESS;\r
   //\r
   // Allocate runtime memory for variable driver global structure.\r
   //\r
@@ -2250,249 +4165,140 @@ VariableCommonInitialize (
     return EFI_OUT_OF_RESOURCES;\r
   }\r
 \r
-  EfiInitializeLock(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock, TPL_NOTIFY);\r
-\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 (FixedPcdGet32(PcdHwErrStorageSize) <= FixedPcdGet32(PcdFlashNvStorageVariableSize));\r
+  InitializeLock (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock, TPL_NOTIFY);\r
 \r
   //\r
-  // Allocate memory for volatile variable store, note that there is a scratch space to store scratch data.\r
+  // Init non-volatile variable store.\r
   //\r
-  ScratchSize = MAX(FixedPcdGet32(PcdMaxVariableSize), FixedPcdGet32(PcdMaxHardwareErrorVariableSize));\r
-  VolatileVariableStore = AllocateRuntimePool (FixedPcdGet32(PcdVariableStoreSize) + ScratchSize);\r
-  if (VolatileVariableStore == NULL) {\r
+  NvFvHeader = NULL;\r
+  Status = InitNonVolatileVariableStore (&NvFvHeader);\r
+  if (EFI_ERROR (Status)) {\r
     FreePool (mVariableModuleGlobal);\r
-    return EFI_OUT_OF_RESOURCES;\r
+    return Status;\r
   }\r
 \r
-  SetMem (VolatileVariableStore, FixedPcdGet32(PcdVariableStoreSize) + ScratchSize, 0xff);\r
-\r
-  //\r
-  //  Variable Specific Data\r
-  //\r
-  mVariableModuleGlobal->VariableGlobal.VolatileVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VolatileVariableStore;\r
-  mVariableModuleGlobal->VolatileLastVariableOffset = (UINTN) GetStartPointer (VolatileVariableStore) - (UINTN) VolatileVariableStore;\r
-  mVariableModuleGlobal->FvbInstance = FvbProtocol;\r
-\r
-  CopyGuid (&VolatileVariableStore->Signature, &gEfiVariableGuid);\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
-\r
-  //\r
-  // Get non volatile varaible store\r
-  //\r
-\r
-  TempVariableStoreHeader = (EFI_PHYSICAL_ADDRESS) 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
+  // mVariableModuleGlobal->VariableGlobal.AuthFormat\r
+  // has been initialized in InitNonVolatileVariableStore().\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
-  if (EFI_ERROR (Status)) {\r
-    goto Done;\r
+  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {\r
+    DEBUG ((EFI_D_INFO, "Variable driver will work with auth variable format!\n"));\r
+    //\r
+    // Set AuthSupport to FALSE first, VariableWriteServiceInitialize() will initialize it.\r
+    //\r
+    mVariableModuleGlobal->VariableGlobal.AuthSupport = FALSE;\r
+    VariableGuid = &gEfiAuthenticatedVariableGuid;\r
+  } else {\r
+    DEBUG ((EFI_D_INFO, "Variable driver will work without auth variable support!\n"));\r
+    mVariableModuleGlobal->VariableGlobal.AuthSupport = FALSE;\r
+    VariableGuid = &gEfiVariableGuid;\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
+  // Get HOB variable store.\r
   //\r
-  mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;\r
-  VariableStoreHeader = (VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase;\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
+  IsNormalVariableHob = FALSE;\r
+  GuidHob = GetFirstGuidHob (VariableGuid);\r
+  if (GuidHob == NULL && VariableGuid == &gEfiAuthenticatedVariableGuid) {\r
     //\r
-    // Parse non-volatile variable data and get last variable offset\r
+    // Try getting it from normal variable HOB\r
     //\r
-    NextVariable  = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase);\r
-    Status        = EFI_SUCCESS;\r
-\r
-    while (IsValidVariableHeader (NextVariable)) {\r
-      UINTN VariableSize = 0;\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
+    GuidHob = GetFirstGuidHob (&gEfiVariableGuid);\r
+    IsNormalVariableHob = TRUE;\r
+  }\r
+  if (GuidHob != NULL) {\r
+    VariableStoreHeader = GET_GUID_HOB_DATA (GuidHob);\r
+    VariableStoreLength = GuidHob->Header.HobLength - sizeof (EFI_HOB_GUID_TYPE);\r
+    if (GetVariableStoreStatus (VariableStoreHeader) == EfiValid) {\r
+      if (IsNormalVariableHob == FALSE) {\r
+        mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) AllocateRuntimeCopyPool ((UINTN) VariableStoreLength, (VOID *) VariableStoreHeader);\r
       } else {\r
-        mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VariableSize);\r
+        mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) ConvertNormalVarStorageToAuthVarStorage ((VOID *) VariableStoreHeader);\r
       }\r
-\r
-      NextVariable = GetNextVariablePtr (NextVariable);\r
-    }\r
-\r
-    mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (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 *) (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
-\r
-        break;\r
+      if (mVariableModuleGlobal->VariableGlobal.HobVariableBase == 0) {\r
+        FreePool (NvFvHeader);\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
-    // 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
-  } else {\r
-    Status = EFI_VOLUME_CORRUPTED;\r
-    DEBUG((EFI_D_INFO, "Variable Store header is corrupted\n"));\r
   }\r
 \r
-Done:\r
-  if (EFI_ERROR (Status)) {\r
+  //\r
+  // Allocate memory for volatile variable store, note that there is a scratch space to store scratch data.\r
+  //\r
+  ScratchSize = GetNonVolatileMaxVariableSize ();\r
+  mVariableModuleGlobal->ScratchBufferSize = ScratchSize;\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 (NvFvHeader);\r
     FreePool (mVariableModuleGlobal);\r
-    FreePool (VolatileVariableStore);\r
+    return EFI_OUT_OF_RESOURCES;\r
   }\r
 \r
-  return Status;\r
+  SetMem (VolatileVariableStore, PcdGet32 (PcdVariableStoreSize) + ScratchSize, 0xff);\r
+\r
+  //\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
+  CopyGuid (&VolatileVariableStore->Signature, VariableGuid);\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
+  return EFI_SUCCESS;\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
+  Get the proper fvb handle and/or fvb protocol by the given Flash address.\r
 \r
-  @param  Event        Event whose notification function is being invoked\r
-  @param  Context      Pointer to the notification function's context\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
-VOID\r
-EFIAPI\r
-VariableClassAddressChangeEvent (\r
-  IN EFI_EVENT        Event,\r
-  IN VOID             *Context\r
-  )\r
-{\r
-  EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->FvbInstance->GetBlockSize);\r
-  EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->FvbInstance->GetPhysicalAddress);\r
-  EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->FvbInstance->GetAttributes);\r
-  EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->FvbInstance->SetAttributes);\r
-  EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->FvbInstance->Read);\r
-  EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->FvbInstance->Write);\r
-  EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->FvbInstance->EraseBlocks);\r
-  EfiConvertPointer (0x0, (VOID **) &mVariableModuleGlobal->FvbInstance);\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
-VOID\r
-EFIAPI\r
-FvbNotificationEvent (\r
-  IN  EFI_EVENT       Event,\r
-  IN  VOID            *Context\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
-  EFI_SYSTEM_TABLE                    *SystemTable;\r
-  EFI_PHYSICAL_ADDRESS                NvStorageVariableBase;\r
-\r
-  SystemTable = (EFI_SYSTEM_TABLE *)Context;\r
-  Fvb         = NULL;\r
-  \r
-  //\r
-  // Locate all handles of Fvb protocol\r
-  //\r
-  Status = gBS->LocateHandleBuffer (\r
-                  ByProtocol,\r
-                  &gEfiFirmwareVolumeBlockProtocolGuid,\r
-                  NULL,\r
-                  &HandleCount,\r
-                  &HandleBuffer\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_FVB_ATTRIBUTES_2                    Attributes;\r
+  UINTN                                   BlockSize;\r
+  UINTN                                   NumberOfBlocks;\r
+\r
+  HandleBuffer = NULL;\r
+  //\r
+  // Get all FVB handles.\r
+  //\r
+  Status = GetFvbCountAndBuffer (&HandleCount, &HandleBuffer);\r
   if (EFI_ERROR (Status)) {\r
-    return ;\r
+    return EFI_NOT_FOUND;\r
   }\r
-  \r
+\r
   //\r
-  // Get the FVB to access variable store\r
+  // Get the FVB to access variable store.\r
   //\r
+  Fvb = NULL;\r
   for (Index = 0; Index < HandleCount; Index += 1, Status = EFI_NOT_FOUND, Fvb = NULL) {\r
-    Status = gBS->HandleProtocol (\r
-                    HandleBuffer[Index],\r
-                    &gEfiFirmwareVolumeBlockProtocolGuid,\r
-                    (VOID **) &Fvb\r
-                    );\r
+    Status = GetFvbByHandle (HandleBuffer[Index], &Fvb);\r
     if (EFI_ERROR (Status)) {\r
       Status = EFI_NOT_FOUND;\r
       break;\r
@@ -2503,94 +4309,42 @@ FvbNotificationEvent (
     //\r
     Status = Fvb->GetAttributes (Fvb, &Attributes);\r
     if (EFI_ERROR (Status) || ((Attributes & EFI_FVB2_WRITE_STATUS) == 0)) {\r
-      continue;     \r
+      continue;\r
     }\r
+\r
     //\r
-    // Compare the address and select the right one\r
+    // Compare the address and select the right one.\r
     //\r
     Status = Fvb->GetPhysicalAddress (Fvb, &FvbBaseAddress);\r
     if (EFI_ERROR (Status)) {\r
       continue;\r
     }\r
 \r
-    FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *) ((UINTN) FvbBaseAddress);\r
-    NvStorageVariableBase = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageVariableBase);\r
-    if ((NvStorageVariableBase >= FvbBaseAddress) && (NvStorageVariableBase < (FvbBaseAddress + FwVolHeader->FvLength))) {\r
-      Status      = EFI_SUCCESS;\r
+    //\r
+    // Assume one FVB has one type of BlockSize.\r
+    //\r
+    Status = Fvb->GetBlockSize (Fvb, 0, &BlockSize, &NumberOfBlocks);\r
+    if (EFI_ERROR (Status)) {\r
+      continue;\r
+    }\r
+\r
+    if ((Address >= FvbBaseAddress) && (Address < (FvbBaseAddress + BlockSize * NumberOfBlocks))) {\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
   FreePool (HandleBuffer);\r
-  if (!EFI_ERROR (Status) && Fvb != NULL) {\r
-    //\r
-    // Close the notify event to avoid install gEfiVariableArchProtocolGuid & gEfiVariableWriteArchProtocolGuid again.\r
-    //\r
-    Status = gBS->CloseEvent (Event);  \r
-    ASSERT_EFI_ERROR (Status);\r
 \r
-    Status = VariableCommonInitialize (Fvb);\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->CreateEventEx (\r
-                  EVT_NOTIFY_SIGNAL,\r
-                  TPL_NOTIFY,\r
-                  VariableClassAddressChangeEvent,\r
-                  NULL,\r
-                  &gEfiEventVirtualAddressChangeGuid,\r
-                  &mVirtualAddressChangeEvent\r
-                  );\r
-    ASSERT_EFI_ERROR (Status);\r
+  if (Fvb == NULL) {\r
+    Status = EFI_NOT_FOUND;\r
   }\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
-  //\r
-  // Register FvbNotificationEvent () notify function.\r
-  // \r
-  EfiCreateProtocolNotifyEvent (\r
-    &gEfiFirmwareVolumeBlockProtocolGuid,\r
-    TPL_CALLBACK,\r
-    FvbNotificationEvent,\r
-    (VOID *)SystemTable,\r
-    &mFvbRegistration\r
-    );\r
-\r
-  return EFI_SUCCESS;\r
+  return Status;\r
 }\r
 \r