]> git.proxmox.com Git - mirror_edk2.git/blobdiff - SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.c
Calculate enough space for 2 variables (public key and variable data) instead of...
[mirror_edk2.git] / SecurityPkg / VariableAuthenticated / RuntimeDxe / Variable.c
index a0419f080de75ab5ec211117c966a5d9c1a63660..7d7bc9e0e121314aae642066500eb431ab6df2e1 100644 (file)
@@ -16,7 +16,7 @@
   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) 2009 - 2013, Intel Corporation. All rights reserved.<BR>\r
+Copyright (c) 2009 - 2014, Intel Corporation. All rights reserved.<BR>\r
 This program and the accompanying materials\r
 are licensed and made available under the terms and conditions of the BSD License\r
 which accompanies this distribution.  The full text of the license may be found at\r
@@ -610,7 +610,7 @@ IsValidPubKeyIndex (
     return FALSE;\r
   }\r
   \r
-  Variable = GetStartPointer (mNvVariableCache);\r
+  Variable = GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase);\r
   \r
   while (IsValidVariableHeader (Variable)) {\r
     if ((Variable->State == VAR_ADDED || Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) && \r
@@ -701,6 +701,7 @@ PubKeyStoreFilter (
   *NewPubKeyIndex = AllocateZeroPool ((PubKeyNumber + 1) * sizeof (UINT32));\r
   if (*NewPubKeyIndex == NULL) {\r
     FreePool (*NewPubKeyStore);\r
+    *NewPubKeyStore = NULL;\r
     return EFI_OUT_OF_RESOURCES;\r
   }\r
 \r
@@ -731,11 +732,12 @@ PubKeyStoreFilter (
   @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
   @param[in]      ReclaimPubKeyStore      Reclaim for public key database or not.\r
-  @param[in]      ReclaimAnyway           If TRUE, do reclaim anyway.\r
   \r
   @return EFI_SUCCESS                  Reclaim operation has finished successfully.\r
-  @return EFI_OUT_OF_RESOURCES         No enough memory resources.\r
+  @return EFI_OUT_OF_RESOURCES         No enough memory resources or variable space.\r
   @return EFI_DEVICE_ERROR             The public key database doesn't exist.\r
   @return Others                       Unexpect error happened during reclaim operation.\r
 \r
@@ -746,8 +748,9 @@ Reclaim (
   OUT    UINTN                        *LastVariableOffset,\r
   IN     BOOLEAN                      IsVolatile,\r
   IN OUT VARIABLE_POINTER_TRACK       *UpdatingPtrTrack,\r
-  IN     BOOLEAN                      ReclaimPubKeyStore,\r
-  IN     BOOLEAN                      ReclaimAnyway\r
+  IN     VARIABLE_HEADER              *NewVariable,\r
+  IN     UINTN                        NewVariableSize,\r
+  IN     BOOLEAN                      ReclaimPubKeyStore\r
   )\r
 {\r
   VARIABLE_HEADER       *Variable;\r
@@ -758,31 +761,28 @@ Reclaim (
   UINT8                 *ValidBuffer;\r
   UINTN                 MaximumBufferSize;\r
   UINTN                 VariableSize;\r
-  UINTN                 VariableNameSize;\r
-  UINTN                 UpdatingVariableNameSize;\r
   UINTN                 NameSize;\r
   UINT8                 *CurrPtr;\r
   VOID                  *Point0;\r
   VOID                  *Point1;\r
   BOOLEAN               FoundAdded;\r
   EFI_STATUS            Status;\r
-  CHAR16                *VariableNamePtr;\r
-  CHAR16                *UpdatingVariableNamePtr;\r
   UINTN                 CommonVariableTotalSize;\r
   UINTN                 HwErrVariableTotalSize;\r
   UINT32                *NewPubKeyIndex;\r
   UINT8                 *NewPubKeyStore;\r
   UINT32                NewPubKeySize;\r
   VARIABLE_HEADER       *PubKeyHeader;\r
-  BOOLEAN               NeedDoReclaim;\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
-  NeedDoReclaim = FALSE;\r
   VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) VariableBase);\r
 \r
   CommonVariableTotalSize = 0;\r
@@ -791,40 +791,50 @@ Reclaim (
   NewPubKeyStore = NULL;\r
   NewPubKeySize  = 0;\r
   PubKeyHeader   = NULL;\r
-  \r
-  //\r
-  // Start Pointers for the variable.\r
-  //\r
-  Variable          = GetStartPointer (VariableStoreHeader);\r
-  MaximumBufferSize = sizeof (VARIABLE_STORE_HEADER);\r
 \r
-  while (IsValidVariableHeader (Variable)) {\r
-    NextVariable = GetNextVariablePtr (Variable);\r
-    if (Variable->State == VAR_ADDED ||\r
-        Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)\r
-       ) {\r
-      VariableSize = (UINTN) NextVariable - (UINTN) Variable;\r
-      MaximumBufferSize += VariableSize;\r
-    } else {\r
-      NeedDoReclaim = TRUE;\r
-    }\r
+  if (IsVolatile) {\r
+    //\r
+    // Start Pointers for the variable.\r
+    //\r
+    Variable          = GetStartPointer (VariableStoreHeader);\r
+    MaximumBufferSize = sizeof (VARIABLE_STORE_HEADER);\r
 \r
-    Variable = NextVariable;\r
-  }\r
+    while (IsValidVariableHeader (Variable)) {\r
+      NextVariable = GetNextVariablePtr (Variable);\r
+      if ((Variable->State == VAR_ADDED || Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) &&\r
+          Variable != UpdatingVariable &&\r
+          Variable != UpdatingInDeletedTransition\r
+         ) {\r
+        VariableSize = (UINTN) NextVariable - (UINTN) Variable;\r
+        MaximumBufferSize += VariableSize;\r
+      }\r
 \r
-  if (!ReclaimAnyway && !NeedDoReclaim) {\r
-    DEBUG ((EFI_D_INFO, "Variable driver: no DELETED variable found, so no variable space could be reclaimed.\n"));\r
-    return EFI_SUCCESS;\r
-  }\r
+      Variable = NextVariable;\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
+    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
@@ -836,6 +846,7 @@ Reclaim (
   CurrPtr = (UINT8 *) GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer);\r
 \r
   if (ReclaimPubKeyStore) {\r
+    ASSERT (IsVolatile == FALSE);\r
     //\r
     // Trim the PubKeyStore and get new PubKeyIndex.\r
     //\r
@@ -847,14 +858,13 @@ Reclaim (
                &NewPubKeySize\r
                );\r
     if (EFI_ERROR (Status)) {\r
-      FreePool (ValidBuffer);\r
-      return Status;\r
+      goto Done;\r
     }\r
 \r
     //\r
     // Refresh the PubKeyIndex for all valid variables (ADDED and IN_DELETED_TRANSITION).\r
     //\r
-    Variable = GetStartPointer (mNvVariableCache);\r
+    Variable = GetStartPointer (VariableStoreHeader);\r
     while (IsValidVariableHeader (Variable)) {\r
       NextVariable = GetNextVariablePtr (Variable);\r
       if (Variable->State == VAR_ADDED || Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
@@ -872,9 +882,9 @@ Reclaim (
         CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize);\r
         ((VARIABLE_HEADER*) CurrPtr)->PubKeyIndex = NewPubKeyIndex[Variable->PubKeyIndex];\r
         CurrPtr += VariableSize;\r
-        if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {\r
+        if ((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
+        } else if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
           CommonVariableTotalSize += VariableSize;\r
         }\r
       }\r
@@ -886,10 +896,8 @@ Reclaim (
     //\r
     ASSERT (PubKeyHeader != NULL);\r
     if (PubKeyHeader == NULL) {\r
-      FreePool (ValidBuffer);\r
-      FreePool (NewPubKeyIndex);\r
-      FreePool (NewPubKeyStore);\r
-      return EFI_DEVICE_ERROR;\r
+      Status = EFI_DEVICE_ERROR;\r
+      goto Done;\r
     }\r
     CopyMem (CurrPtr, (UINT8*) PubKeyHeader, sizeof (VARIABLE_HEADER));\r
     Variable = (VARIABLE_HEADER*) CurrPtr;\r
@@ -905,25 +913,7 @@ Reclaim (
     Variable = GetStartPointer (VariableStoreHeader);\r
     while (IsValidVariableHeader (Variable)) {\r
       NextVariable = GetNextVariablePtr (Variable);\r
-      if (Variable->State == VAR_ADDED) {\r
-        if (UpdatingVariable != NULL) {\r
-          if (UpdatingVariable == Variable) {\r
-            Variable = NextVariable;\r
-            continue;\r
-          }\r
-\r
-          VariableNameSize         = NameSizeOfVariable(Variable);\r
-          UpdatingVariableNameSize = NameSizeOfVariable(UpdatingVariable);\r
-\r
-          VariableNamePtr         = GetVariableNamePtr (Variable);\r
-          UpdatingVariableNamePtr = GetVariableNamePtr (UpdatingVariable);\r
-          if (CompareGuid (&Variable->VendorGuid, &UpdatingVariable->VendorGuid)    &&\r
-              VariableNameSize == UpdatingVariableNameSize &&\r
-              CompareMem (VariableNamePtr, UpdatingVariableNamePtr, VariableNameSize) == 0 ) {\r
-            Variable = NextVariable;\r
-            continue;\r
-          }\r
-        }\r
+      if (Variable != UpdatingVariable && Variable->State == VAR_ADDED) {\r
         VariableSize = (UINTN) NextVariable - (UINTN) Variable;\r
         CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize);\r
         CurrPtr += VariableSize;\r
@@ -936,29 +926,13 @@ Reclaim (
       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
-      UpdatingPtrTrack->CurrPtr = (VARIABLE_HEADER *)((UINTN)UpdatingPtrTrack->StartPtr + ((UINTN)CurrPtr - (UINTN)GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer)));\r
-      UpdatingPtrTrack->InDeletedTransitionPtr = NULL;\r
-      CurrPtr += VariableSize;\r
-      if ((!IsVolatile) && ((UpdatingVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {\r
-          HwErrVariableTotalSize += VariableSize;\r
-      } else if ((!IsVolatile) && ((UpdatingVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {\r
-          CommonVariableTotalSize += VariableSize;\r
-      }\r
-    }\r
-\r
     //\r
     // Reinstall all in delete transition variables.\r
     //\r
-    Variable      = GetStartPointer (VariableStoreHeader);\r
+    Variable = GetStartPointer (VariableStoreHeader);\r
     while (IsValidVariableHeader (Variable)) {\r
       NextVariable = GetNextVariablePtr (Variable);\r
-      if (Variable != UpdatingVariable && Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
+      if (Variable != UpdatingVariable && Variable != UpdatingInDeletedTransition && Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
 \r
         //\r
         // Buffer has cached all ADDED variable.\r
@@ -1001,6 +975,42 @@ Reclaim (
 \r
       Variable = NextVariable;\r
     }\r
+\r
+    //\r
+    // Install the new variable if it is not NULL.\r
+    //\r
+    if (NewVariable != NULL) {\r
+      if ((UINTN) (CurrPtr - ValidBuffer) + NewVariableSize > VariableStoreHeader->Size) {\r
+        //\r
+        // No enough space to store the new variable.\r
+        //\r
+        Status = EFI_OUT_OF_RESOURCES;\r
+        goto Done;\r
+      }\r
+      if (!IsVolatile) {\r
+        if ((NewVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+          HwErrVariableTotalSize += NewVariableSize;\r
+        } else if ((NewVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+          CommonVariableTotalSize += NewVariableSize;\r
+        }\r
+        if ((HwErrVariableTotalSize > PcdGet32 (PcdHwErrStorageSize)) ||\r
+            (CommonVariableTotalSize > VariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize))) {\r
+          //\r
+          // No enough space to store the new variable by NV or NV+HR attribute.\r
+          //\r
+          Status = EFI_OUT_OF_RESOURCES;\r
+          goto Done;\r
+        }\r
+      }\r
+\r
+      CopyMem (CurrPtr, (UINT8 *) NewVariable, NewVariableSize);\r
+      ((VARIABLE_HEADER *) CurrPtr)->State = VAR_ADDED;\r
+      if (UpdatingVariable != NULL) {\r
+        UpdatingPtrTrack->CurrPtr = (VARIABLE_HEADER *)((UINTN)UpdatingPtrTrack->StartPtr + ((UINTN)CurrPtr - (UINTN)GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer)));\r
+        UpdatingPtrTrack->InDeletedTransitionPtr = NULL;\r
+      }\r
+      CurrPtr += NewVariableSize;\r
+    }\r
   }\r
 \r
   if (IsVolatile) {\r
@@ -1008,7 +1018,8 @@ Reclaim (
     // 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
+    CopyMem ((UINT8 *) (UINTN) VariableBase, ValidBuffer, (UINTN) (CurrPtr - ValidBuffer));\r
+    *LastVariableOffset = (UINTN) (CurrPtr - ValidBuffer);\r
     Status  = EFI_SUCCESS;\r
   } else {\r
     //\r
@@ -1016,41 +1027,45 @@ Reclaim (
     //\r
     Status = FtwVariableSpace (\r
               VariableBase,\r
-              ValidBuffer,\r
-              (UINTN) (CurrPtr - (UINT8 *) ValidBuffer)\r
+              (VARIABLE_STORE_HEADER *) ValidBuffer\r
               );\r
-    CopyMem (mNvVariableCache, (CHAR8 *)(UINTN)VariableBase, VariableStoreHeader->Size);\r
-  }\r
-  if (!EFI_ERROR (Status)) {\r
-    *LastVariableOffset = (UINTN) (CurrPtr - (UINT8 *) ValidBuffer);\r
-    if (!IsVolatile) {\r
+    if (!EFI_ERROR (Status)) {\r
+      *LastVariableOffset = (UINTN) (CurrPtr - ValidBuffer);\r
       mVariableModuleGlobal->HwErrVariableTotalSize = HwErrVariableTotalSize;\r
       mVariableModuleGlobal->CommonVariableTotalSize = CommonVariableTotalSize;\r
-    }\r
-  } else {\r
-    NextVariable  = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableBase);\r
-    while (IsValidVariableHeader (NextVariable)) {\r
-      VariableSize = NextVariable->NameSize + NextVariable->DataSize + sizeof (VARIABLE_HEADER);\r
-      if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {\r
-        mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VariableSize);\r
-      } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {\r
-        mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VariableSize);\r
-      }\r
+    } else {\r
+      NextVariable  = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableBase);\r
+      while (IsValidVariableHeader (NextVariable)) {\r
+        VariableSize = NextVariable->NameSize + NextVariable->DataSize + sizeof (VARIABLE_HEADER);\r
+        if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+          mVariableModuleGlobal->HwErrVariableTotalSize += HEADER_ALIGN (VariableSize);\r
+        } else if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+          mVariableModuleGlobal->CommonVariableTotalSize += HEADER_ALIGN (VariableSize);\r
+        }\r
 \r
-      NextVariable = GetNextVariablePtr (NextVariable);\r
+        NextVariable = GetNextVariablePtr (NextVariable);\r
+      }\r
+      *LastVariableOffset = (UINTN) NextVariable - (UINTN) VariableBase;\r
     }\r
-    *LastVariableOffset = (UINTN) NextVariable - (UINTN) VariableBase;\r
   }\r
 \r
-  if (NewPubKeyStore != NULL) {\r
-    FreePool (NewPubKeyStore);\r
-  }\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
-  if (NewPubKeyIndex != NULL) {\r
-    FreePool (NewPubKeyIndex);\r
+    if (NewPubKeyStore != NULL) {\r
+      FreePool (NewPubKeyStore);\r
+    }\r
+\r
+    if (NewPubKeyIndex != NULL) {\r
+      FreePool (NewPubKeyIndex);\r
+    }\r
   }\r
-  \r
-  FreePool (ValidBuffer);\r
 \r
   return Status;\r
 }\r
@@ -1493,6 +1508,134 @@ VariableGetBestLanguage (
   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 ...                    The variable argument list with type VARIABLE_ENTRY_CONSISTENCY *.\r
+                                A NULL terminates the list. The VariableSize of \r
+                                VARIABLE_ENTRY_CONSISTENCY is the variable data size as input.\r
+                                It will be changed to variable total size as output.\r
+\r
+  @retval TRUE                  Have enough variable space to set the Variables successfully.\r
+  @retval FALSE                 No enough variable space to set the Variables successfully.\r
+\r
+**/\r
+BOOLEAN\r
+EFIAPI\r
+CheckRemainingSpaceForConsistency (\r
+  IN UINT32                     Attributes,\r
+  ...\r
+  )\r
+{\r
+  EFI_STATUS                    Status;\r
+  VA_LIST                       Args;\r
+  VARIABLE_ENTRY_CONSISTENCY    *VariableEntry;\r
+  UINT64                        MaximumVariableStorageSize;\r
+  UINT64                        RemainingVariableStorageSize;\r
+  UINT64                        MaximumVariableSize;\r
+  UINTN                         TotalNeededSize;\r
+  UINTN                         OriginalVarSize;\r
+  VARIABLE_STORE_HEADER         *VariableStoreHeader;\r
+  VARIABLE_POINTER_TRACK        VariablePtrTrack;\r
+  VARIABLE_HEADER               *NextVariable;\r
+  UINTN                         VarNameSize;\r
+  UINTN                         VarDataSize;\r
+\r
+  //\r
+  // Non-Volatile related.\r
+  //\r
+  VariableStoreHeader = mNvVariableCache;\r
+\r
+  Status = VariableServiceQueryVariableInfoInternal (\r
+             Attributes,\r
+             &MaximumVariableStorageSize,\r
+             &RemainingVariableStorageSize,\r
+             &MaximumVariableSize\r
+             );\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  TotalNeededSize = 0;\r
+  VA_START (Args, Attributes);\r
+  VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);\r
+  while (VariableEntry != NULL) {\r
+    //\r
+    // Calculate variable total size.\r
+    //\r
+    VarNameSize  = StrSize (VariableEntry->Name);\r
+    VarNameSize += GET_PAD_SIZE (VarNameSize);\r
+    VarDataSize  = VariableEntry->VariableSize;\r
+    VarDataSize += GET_PAD_SIZE (VarDataSize);\r
+    VariableEntry->VariableSize = HEADER_ALIGN (sizeof (VARIABLE_HEADER) + VarNameSize + VarDataSize);\r
+\r
+    TotalNeededSize += VariableEntry->VariableSize;\r
+    VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);\r
+  }\r
+  VA_END (Args);\r
+\r
+  if (RemainingVariableStorageSize >= TotalNeededSize) {\r
+    //\r
+    // Already have enough space.\r
+    //\r
+    return TRUE;\r
+  } else if (AtRuntime ()) {\r
+    //\r
+    // At runtime, no reclaim.\r
+    // The original variable space of Variables can't be reused.\r
+    //\r
+    return FALSE;\r
+  }\r
+\r
+  VA_START (Args, Attributes);\r
+  VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);\r
+  while (VariableEntry != NULL) {\r
+    //\r
+    // Check if Variable[Index] has been present and get its size.\r
+    //\r
+    OriginalVarSize = 0;\r
+    VariablePtrTrack.StartPtr = GetStartPointer (VariableStoreHeader);\r
+    VariablePtrTrack.EndPtr   = GetEndPointer   (VariableStoreHeader);\r
+    Status = FindVariableEx (\r
+               VariableEntry->Name,\r
+               VariableEntry->Guid,\r
+               FALSE,\r
+               &VariablePtrTrack\r
+               );\r
+    if (!EFI_ERROR (Status)) {\r
+      //\r
+      // Get size of Variable[Index].\r
+      //\r
+      NextVariable = GetNextVariablePtr (VariablePtrTrack.CurrPtr);\r
+      OriginalVarSize = (UINTN) NextVariable - (UINTN) VariablePtrTrack.CurrPtr;\r
+      //\r
+      // Add the original size of Variable[Index] to remaining variable storage size.\r
+      //\r
+      RemainingVariableStorageSize += OriginalVarSize;\r
+    }\r
+    if (VariableEntry->VariableSize > RemainingVariableStorageSize) {\r
+      //\r
+      // No enough space for Variable[Index].\r
+      //\r
+      VA_END (Args);\r
+      return FALSE;\r
+    }\r
+    //\r
+    // Sub the (new) size of Variable[Index] from remaining variable storage size.\r
+    //\r
+    RemainingVariableStorageSize -= VariableEntry->VariableSize;\r
+    VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);\r
+  }\r
+  VA_END (Args);\r
+\r
+  return TRUE;\r
+}\r
+\r
 /**\r
   Hook the operations in PlatformLangCodes, LangCodes, PlatformLang and Lang.\r
 \r
@@ -1507,8 +1650,13 @@ VariableGetBestLanguage (
 \r
   @param[in] DataSize           Size of data. 0 means delete.\r
 \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
-VOID\r
+EFI_STATUS\r
 AutoUpdateLangVariable (\r
   IN  CHAR16             *VariableName,\r
   IN  VOID               *Data,\r
@@ -1522,12 +1670,13 @@ AutoUpdateLangVariable (
   UINT32                 Attributes;\r
   VARIABLE_POINTER_TRACK Variable;\r
   BOOLEAN                SetLanguageCodes;\r
+  VARIABLE_ENTRY_CONSISTENCY VariableEntry[2];\r
 \r
   //\r
   // Don't do updates for delete operation\r
   //\r
   if (DataSize == 0) {\r
-    return;\r
+    return EFI_SUCCESS;\r
   }\r
 \r
   SetLanguageCodes = FALSE;\r
@@ -1537,7 +1686,7 @@ AutoUpdateLangVariable (
     // PlatformLangCodes is a volatile variable, so it can not be updated at runtime.\r
     //\r
     if (AtRuntime ()) {\r
-      return;\r
+      return EFI_WRITE_PROTECTED;\r
     }\r
 \r
     SetLanguageCodes = TRUE;\r
@@ -1567,7 +1716,7 @@ AutoUpdateLangVariable (
     // LangCodes is a volatile variable, so it can not be updated at runtime.\r
     //\r
     if (AtRuntime ()) {\r
-      return;\r
+      return EFI_WRITE_PROTECTED;\r
     }\r
 \r
     SetLanguageCodes = TRUE;\r
@@ -1611,11 +1760,13 @@ AutoUpdateLangVariable (
         //\r
         // Neither PlatformLang nor Lang is set, directly return\r
         //\r
-        return;\r
+        return EFI_SUCCESS;\r
       }\r
     }\r
   }\r
 \r
+  Status = EFI_SUCCESS;\r
+\r
   //\r
   // According to UEFI spec, "Lang" and "PlatformLang" is NV|BS|RT attributions.\r
   //\r
@@ -1642,16 +1793,31 @@ AutoUpdateLangVariable (
         BestLang = GetLangFromSupportedLangCodes (mVariableModuleGlobal->LangCodes, Index, TRUE);\r
 \r
         //\r
-        // Successfully convert PlatformLang to Lang, and set the BestLang value into Lang variable simultaneously.\r
+        // Check the variable space for both Lang and PlatformLang variable.\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
+        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
-        DEBUG ((EFI_D_INFO, "Variable Driver Auto Update PlatformLang, PlatformLang:%a, Lang:%a\n", BestPlatformLang, BestLang));\r
+          Status = UpdateVariable (EFI_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, BestLang,\r
+                                   ISO_639_2_ENTRY_SIZE + 1, Attributes, 0, 0, &Variable, NULL);\r
+        }\r
 \r
-        ASSERT_EFI_ERROR(Status);\r
+        DEBUG ((EFI_D_INFO, "Variable Driver Auto Update PlatformLang, PlatformLang:%a, Lang:%a Status: %r\n", BestPlatformLang, BestLang, Status));\r
       }\r
     }\r
 \r
@@ -1676,18 +1842,43 @@ AutoUpdateLangVariable (
         BestPlatformLang = GetLangFromSupportedLangCodes (mVariableModuleGlobal->PlatformLangCodes, Index, FALSE);\r
 \r
         //\r
-        // Successfully convert Lang to PlatformLang, and set the BestPlatformLang value into PlatformLang variable simultaneously.\r
+        // Check the variable space for both PlatformLang and Lang variable.\r
         //\r
-        FindVariable (EFI_PLATFORM_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\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 (EFI_PLATFORM_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, BestPlatformLang,\r
-                                 AsciiStrSize (BestPlatformLang), Attributes, 0, 0, &Variable, NULL);\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
 }\r
 \r
 /**\r
@@ -1737,7 +1928,9 @@ UpdateVariable (
   VARIABLE_POINTER_TRACK              NvVariable;\r
   VARIABLE_STORE_HEADER               *VariableStoreHeader;\r
   UINTN                               CacheOffset;\r
-  UINTN                               BufSize;\r
+  UINT8                               *BufferForMerge;\r
+  UINTN                               MergedBufSize;\r
+  BOOLEAN                             DataReady;\r
   UINTN                               DataOffset;\r
 \r
   if (mVariableModuleGlobal->FvbInstance == NULL) {\r
@@ -1787,7 +1980,8 @@ UpdateVariable (
   //\r
   NextVariable = GetEndPointer ((VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase));\r
   ScratchSize = MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize));\r
-\r
+  SetMem (NextVariable, ScratchSize, 0xff);\r
+  DataReady = FALSE;\r
 \r
   if (Variable->CurrPtr != NULL) {\r
     //\r
@@ -1879,7 +2073,7 @@ UpdateVariable (
     // then return to the caller immediately.\r
     //\r
     if (DataSizeOfVariable (Variable->CurrPtr) == DataSize &&\r
-        (CompareMem (Data, GetVariableDataPtr (Variable->CurrPtr), DataSize) == 0)  &&\r
+        (CompareMem (Data, GetVariableDataPtr (Variable->CurrPtr), DataSize) == 0) &&\r
         ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) &&\r
         (TimeStamp == NULL)) {\r
       //\r
@@ -1896,42 +2090,42 @@ UpdateVariable (
       //\r
       if ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0) {\r
         //\r
-        // Cache the previous variable data into StorageArea.\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 = sizeof (VARIABLE_HEADER) + Variable->CurrPtr->NameSize + GET_PAD_SIZE (Variable->CurrPtr->NameSize);\r
-        CopyMem (mStorageArea, (UINT8*)((UINTN) Variable->CurrPtr + DataOffset), Variable->CurrPtr->DataSize);\r
+        BufferForMerge = (UINT8 *) ((UINTN) NextVariable + DataOffset);\r
+        CopyMem (BufferForMerge, (UINT8 *) ((UINTN) Variable->CurrPtr + DataOffset), Variable->CurrPtr->DataSize);\r
 \r
         //\r
         // Set Max Common Variable Data Size as default MaxDataSize \r
         //\r
-        MaxDataSize = PcdGet32 (PcdMaxVariableSize) - sizeof (VARIABLE_HEADER) - StrSize (VariableName) - GET_PAD_SIZE (StrSize (VariableName));\r
-\r
+        MaxDataSize = PcdGet32 (PcdMaxVariableSize) - DataOffset;\r
 \r
         if ((CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) &&\r
             ((StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0) || (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE1) == 0))) ||\r
             (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0))) {\r
-\r
           //\r
           // For variables with formatted as EFI_SIGNATURE_LIST, the driver shall not perform an append of\r
           // EFI_SIGNATURE_DATA values that are already part of the existing variable value.\r
           //\r
           Status = AppendSignatureList (\r
-                     mStorageArea, \r
+                     BufferForMerge,\r
                      Variable->CurrPtr->DataSize, \r
                      MaxDataSize - Variable->CurrPtr->DataSize,\r
-                     Data, \r
-                     DataSize, \r
-                     &BufSize\r
+                     Data,\r
+                     DataSize,\r
+                     &MergedBufSize\r
                      );\r
           if (Status == EFI_BUFFER_TOO_SMALL) {\r
             //\r
-            // Signture List is too long, Failed to Append\r
+            // Signature List is too long, Failed to Append.\r
             //\r
             Status = EFI_INVALID_PARAMETER;\r
             goto Done;\r
           }\r
 \r
-          if (BufSize == Variable->CurrPtr->DataSize) {\r
+          if (MergedBufSize == Variable->CurrPtr->DataSize) {\r
             if ((TimeStamp == NULL) || CompareTimeStamp (TimeStamp, &Variable->CurrPtr->TimeStamp)) {\r
               //\r
               // New EFI_SIGNATURE_DATA is not found and timestamp is not later\r
@@ -1944,29 +2138,30 @@ UpdateVariable (
           }\r
         } else {\r
           //\r
-          // For other Variables, append the new data to the end of previous data.\r
+          // For other Variables, append the new data to the end of existing data.\r
           // Max Harware error record variable data size is different from common variable\r
           //\r
           if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
-            MaxDataSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - sizeof (VARIABLE_HEADER) - StrSize (VariableName) - GET_PAD_SIZE (StrSize (VariableName));\r
+            MaxDataSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - DataOffset;\r
           }\r
 \r
           if (Variable->CurrPtr->DataSize + DataSize > MaxDataSize) {\r
             //\r
-            // Exsiting data + Appended data exceed maximum variable size limitation \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) mStorageArea + Variable->CurrPtr->DataSize), Data, DataSize);\r
-          BufSize = Variable->CurrPtr->DataSize + DataSize;\r
+          CopyMem ((UINT8*) ((UINTN) BufferForMerge + Variable->CurrPtr->DataSize), Data, DataSize);\r
+          MergedBufSize = Variable->CurrPtr->DataSize + DataSize;\r
         }\r
 \r
         //\r
-        // Override Data and DataSize which are used for combined data area including previous and new data.\r
+        // BufferForMerge(from DataOffset of NextVariable) has included the merged existing and new data.\r
         //\r
-        Data     = mStorageArea;\r
-        DataSize = BufSize;\r
+        Data      = BufferForMerge;\r
+        DataSize  = MergedBufSize;\r
+        DataReady = TRUE;\r
       }\r
 \r
       //\r
@@ -2023,9 +2218,7 @@ UpdateVariable (
   //\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
-  SetMem (NextVariable, ScratchSize, 0xff);\r
-\r
+  //\r
   NextVariable->StartId     = VARIABLE_DATA;\r
   //\r
   // NextVariable->State = VAR_ADDED;\r
@@ -2067,11 +2260,19 @@ UpdateVariable (
     VarNameSize\r
     );\r
   VarDataOffset = VarNameOffset + VarNameSize + GET_PAD_SIZE (VarNameSize);\r
-  CopyMem (\r
-    (UINT8 *) ((UINTN) NextVariable + VarDataOffset),\r
-    Data,\r
-    DataSize\r
-    );\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 (&NextVariable->VendorGuid, VendorGuid, sizeof (EFI_GUID));\r
   //\r
   // There will be pad bytes after Data, the NextVariable->NameSize and\r
@@ -2101,33 +2302,29 @@ UpdateVariable (
         goto Done;\r
       }\r
       //\r
-      // Perform garbage collection & reclaim operation.\r
+      // Perform garbage collection & reclaim operation, and integrate the new variable at the same time.\r
       //\r
       Status = Reclaim (\r
                  mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,\r
                  &mVariableModuleGlobal->NonVolatileLastVariableOffset,\r
                  FALSE,\r
                  Variable,\r
-                 FALSE,\r
+                 NextVariable,\r
+                 HEADER_ALIGN (VarSize),\r
                  FALSE\r
                  );\r
-      if (EFI_ERROR (Status)) {\r
-        goto Done;\r
-      }\r
-      //\r
-      // If still no enough space, return out of resources.\r
-      //\r
-      if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0)\r
-        && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize)))\r
-        || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0)\r
-        && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > NonVolatileVarableStoreSize - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize)))) {\r
-        Status = EFI_OUT_OF_RESOURCES;\r
-        goto Done;\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
+      if (!EFI_ERROR (Status)) {\r
+        //\r
+        // The new variable has been integrated successfully during reclaiming.\r
+        //\r
+        if (Variable->CurrPtr != NULL) {\r
+          CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));\r
+          CacheVariable->InDeletedTransitionPtr = NULL;\r
+        }\r
+        UpdateVariableInfo (VariableName, VendorGuid, FALSE, FALSE, TRUE, FALSE, FALSE);\r
+        FlushHobVariableToFlash (VariableName, VendorGuid);\r
       }\r
+      goto Done;\r
     }\r
     //\r
     // Four steps\r
@@ -2225,32 +2422,28 @@ UpdateVariable (
     if ((UINT32) (VarSize + mVariableModuleGlobal->VolatileLastVariableOffset) >\r
         ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase)))->Size) {\r
       //\r
-      // Perform garbage collection & reclaim operation.\r
+      // Perform garbage collection & reclaim operation, and integrate the new variable at the same time.\r
       //\r
       Status = Reclaim (\r
                  mVariableModuleGlobal->VariableGlobal.VolatileVariableBase,\r
                  &mVariableModuleGlobal->VolatileLastVariableOffset,\r
                  TRUE,\r
                  Variable,\r
-                 FALSE,\r
+                 NextVariable,\r
+                 HEADER_ALIGN (VarSize),\r
                  FALSE\r
                  );\r
-      if (EFI_ERROR (Status)) {\r
-        goto Done;\r
-      }\r
-      //\r
-      // If still no enough space, return out of resources.\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
-      }\r
-      if (Variable->CurrPtr != NULL) {\r
-        CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));\r
-        CacheVariable->InDeletedTransitionPtr = NULL;\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
+      goto Done;\r
     }\r
 \r
     NextVariable->State = VAR_ADDED;\r
@@ -2969,11 +3162,20 @@ VariableServiceSetVariable (
       goto Done;\r
     }\r
   }\r
-  \r
-  //\r
-  // Hook the operation of setting PlatformLangCodes/PlatformLang and LangCodes/Lang.\r
-  //\r
-  AutoUpdateLangVariable (VariableName, Data, DataSize);\r
+\r
+  if (!FeaturePcdGet (PcdUefiVariableDefaultLangDeprecate)) {\r
+    //\r
+    // Hook the operation of setting PlatformLangCodes/PlatformLang and LangCodes/Lang.\r
+    //\r
+    Status = AutoUpdateLangVariable (VariableName, Data, DataSize);\r
+    if (EFI_ERROR (Status)) {\r
+      //\r
+      // The auto update operation failed, directly return to avoid inconsistency between PlatformLang and Lang.\r
+      //\r
+      goto Done;\r
+    }\r
+  }\r
+\r
   //\r
   // Process PK, KEK, Sigdb seperately.\r
   //\r
@@ -3023,14 +3225,12 @@ Done:
   @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
+VariableServiceQueryVariableInfoInternal (\r
   IN  UINT32                 Attributes,\r
   OUT UINT64                 *MaximumVariableStorageSize,\r
   OUT UINT64                 *RemainingVariableStorageSize,\r
@@ -3043,38 +3243,12 @@ VariableServiceQueryVariableInfo (
   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(MaximumVariableStorageSize == NULL || RemainingVariableStorageSize == NULL || MaximumVariableSize == NULL || Attributes == 0) {\r
-    return EFI_INVALID_PARAMETER;\r
-  }\r
-\r
-  if((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == 0) {\r
-    //\r
-    // Make sure the Attributes combination is supported by the platform.\r
-    //\r
-    return EFI_UNSUPPORTED;\r
-  } else if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {\r
-    //\r
-    // Make sure if runtime bit is set, boot service bit is set also.\r
-    //\r
-    return EFI_INVALID_PARAMETER;\r
-  } else if (AtRuntime () && ((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) {\r
-    //\r
-    // Make sure RT Attribute is set if we are in Runtime phase.\r
-    //\r
-    return EFI_INVALID_PARAMETER;\r
-  } else if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
-    //\r
-    // Make sure Hw Attribute is set with NV.\r
-    //\r
-    return EFI_INVALID_PARAMETER;\r
-  }\r
-\r
-  AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
-\r
   if((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {\r
     //\r
     // Query is Volatile related.\r
@@ -3146,6 +3320,27 @@ VariableServiceQueryVariableInfo (
         } else {\r
           CommonVariableTotalSize += VariableSize;\r
         }\r
+      } else if (Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
+        //\r
+        // If it is a IN_DELETED_TRANSITION variable,\r
+        // and there is not also a same ADDED one at the same time,\r
+        // this IN_DELETED_TRANSITION variable is valid.\r
+        //\r
+        VariablePtrTrack.StartPtr = GetStartPointer (VariableStoreHeader);\r
+        VariablePtrTrack.EndPtr   = GetEndPointer   (VariableStoreHeader);\r
+        Status = FindVariableEx (\r
+                   GetVariableNamePtr (Variable),\r
+                   &Variable->VendorGuid,\r
+                   FALSE,\r
+                   &VariablePtrTrack\r
+                   );\r
+        if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State != VAR_ADDED) {\r
+          if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+            HwErrVariableTotalSize += VariableSize;\r
+          } else {\r
+            CommonVariableTotalSize += VariableSize;\r
+          }\r
+        }\r
       }\r
     }\r
 \r
@@ -3167,10 +3362,79 @@ VariableServiceQueryVariableInfo (
     *MaximumVariableSize = *RemainingVariableStorageSize - sizeof (VARIABLE_HEADER);\r
   }\r
 \r
-  ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\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
+    //\r
+    // Make sure the Attributes combination is supported by the platform.\r
+    //\r
+    return EFI_UNSUPPORTED;\r
+  } else if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {\r
+    //\r
+    // Make sure if runtime bit is set, boot service bit is set also.\r
+    //\r
+    return EFI_INVALID_PARAMETER;\r
+  } else if (AtRuntime () && ((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) {\r
+    //\r
+    // Make sure RT Attribute is set if we are in Runtime phase.\r
+    //\r
+    return EFI_INVALID_PARAMETER;\r
+  } else if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
+    //\r
+    // Make sure Hw Attribute is set with NV.\r
+    //\r
+    return EFI_INVALID_PARAMETER;\r
+  }\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
@@ -3207,7 +3471,8 @@ ReclaimForOS(
             &mVariableModuleGlobal->NonVolatileLastVariableOffset,\r
             FALSE,\r
             NULL,\r
-            FALSE,\r
+            NULL,\r
+            0,\r
             FALSE\r
             );\r
     ASSERT_EFI_ERROR (Status);\r
@@ -3478,8 +3743,9 @@ VariableWriteServiceInitialize (
                  &mVariableModuleGlobal->NonVolatileLastVariableOffset,\r
                  FALSE,\r
                  NULL,\r
-                 FALSE,\r
-                 TRUE\r
+                 NULL,\r
+                 0,\r
+                 FALSE\r
                  );\r
       if (EFI_ERROR (Status)) {\r
         return Status;\r