]> git.proxmox.com Git - mirror_edk2.git/blobdiff - MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
MdeModulePkg/Variable: Fix VS2015 warning about uninitialized local var.
[mirror_edk2.git] / MdeModulePkg / Universal / Variable / RuntimeDxe / Variable.c
index 349128937b4fbc139d616c45b182dfa1198ae6b5..834d2ff7c6db4ee060aaec22ef3956ac7d8241de 100644 (file)
@@ -1,8 +1,7 @@
 /** @file\r
-\r
-  The common variable operation routines shared by DXE_RUNTIME variable \r
+  The common variable operation routines shared by DXE_RUNTIME variable\r
   module and DXE_SMM variable module.\r
-  \r
+\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
   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 - 2015, Intel Corporation. All rights reserved.<BR>\r
-This program and the accompanying materials                          \r
-are licensed and made available under the terms and conditions of the BSD License         \r
-which accompanies this distribution.  The full text of the license may be found at        \r
-http://opensource.org/licenses/bsd-license.php                                            \r
+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
+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
@@ -60,14 +62,62 @@ BOOLEAN                mEnableLocking         = TRUE;
 //\r
 VAR_ERROR_FLAG         mCurrentBootVarErrFlag = VAR_ERROR_FLAG_NO_ERROR;\r
 \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
+AUTH_VAR_LIB_CONTEXT_IN mContextIn = {\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 mContextOut;\r
+\r
+/**\r
+\r
+  SecureBoot Hook for auth variable update.\r
+\r
+  @param[in] VariableName                 Name of Variable to be found.\r
+  @param[in] VendorGuid                   Variable vendor GUID.\r
+**/\r
+VOID\r
+EFIAPI\r
+SecureBootHook (\r
+  IN CHAR16                                 *VariableName,\r
+  IN EFI_GUID                               *VendorGuid\r
+  );\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
@@ -111,11 +161,11 @@ UpdateVariableInfo (
       CopyGuid (&gVariableInfo->VendorGuid, VendorGuid);\r
       gVariableInfo->Name = AllocateZeroPool (StrSize (VariableName));\r
       ASSERT (gVariableInfo->Name != NULL);\r
-      StrnCpy (gVariableInfo->Name, VariableName, StrLen (VariableName));\r
+      StrCpyS (gVariableInfo->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName);\r
       gVariableInfo->Volatile = Volatile;\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
@@ -147,7 +197,7 @@ UpdateVariableInfo (
         CopyGuid (&Entry->Next->VendorGuid, VendorGuid);\r
         Entry->Next->Name = AllocateZeroPool (StrSize (VariableName));\r
         ASSERT (Entry->Next->Name != NULL);\r
-        StrnCpy (Entry->Next->Name, VariableName, StrLen (VariableName));\r
+        StrCpyS (Entry->Next->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName);\r
         Entry->Next->Volatile = Volatile;\r
       }\r
 \r
@@ -236,7 +286,9 @@ UpdateVariableStore (
   // Check if the Data is Volatile.\r
   //\r
   if (!Volatile) {\r
-    ASSERT (Fvb != NULL);\r
+    if (Fvb == NULL) {\r
+      return EFI_INVALID_PARAMETER;\r
+    }\r
     Status = Fvb->GetPhysicalAddress(Fvb, &FvVolHdr);\r
     ASSERT_EFI_ERROR (Status);\r
 \r
@@ -265,14 +317,14 @@ 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
   //\r
@@ -346,7 +398,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
@@ -367,6 +420,27 @@ 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
@@ -382,13 +456,49 @@ 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
@@ -405,13 +515,49 @@ 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
@@ -428,8 +574,30 @@ GetVariableNamePtr (
   IN  VARIABLE_HEADER   *Variable\r
   )\r
 {\r
+  return (CHAR16 *) ((UINTN) Variable + GetVariableHeaderSize ());\r
+}\r
 \r
-  return (CHAR16 *) (Variable + 1);\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
+  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
@@ -447,7 +615,7 @@ GetVariableDataPtr (
   )\r
 {\r
   UINTN Value;\r
-  \r
+\r
   //\r
   // Be careful about pad size for alignment.\r
   //\r
@@ -458,6 +626,30 @@ 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
@@ -514,7 +706,7 @@ GetStartPointer (
 \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
@@ -657,7 +849,10 @@ InitializeVarErrorFlag (
     &Flag,\r
     sizeof (Flag),\r
     VARIABLE_ATTRIBUTE_NV_BS_RT,\r
-    &Variable\r
+    0,\r
+    0,\r
+    &Variable,\r
+    NULL\r
     );\r
 }\r
 \r
@@ -683,7 +878,7 @@ IsUserVariable (
   // then no need to check if the variable is user variable or not specially.\r
   //\r
   if (mEndOfDxe && (mVariableModuleGlobal->CommonMaxUserVariableSpace != mVariableModuleGlobal->CommonVariableSpace)) {\r
-    if (InternalVarCheckVariablePropertyGet (GetVariableNamePtr (Variable), &Variable->VendorGuid, &Property) == EFI_NOT_FOUND) {\r
+    if (InternalVarCheckVariablePropertyGet (GetVariableNamePtr (Variable), GetVendorGuidPtr (Variable), &Property) == EFI_NOT_FOUND) {\r
       return TRUE;\r
     }\r
   }\r
@@ -715,7 +910,7 @@ CalculateCommonUserVariableTotalSize (
       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 (InternalVarCheckVariablePropertyGet (GetVariableNamePtr (Variable), &Variable->VendorGuid, &Property) == EFI_NOT_FOUND) {\r
+        if (InternalVarCheckVariablePropertyGet (GetVariableNamePtr (Variable), GetVendorGuidPtr (Variable), &Property) == EFI_NOT_FOUND) {\r
           //\r
           // No property, it is user variable.\r
           //\r
@@ -752,27 +947,27 @@ InitializeVariableQuota (
 \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 UpdatingPtrTrack        Pointer to updating variable pointer track structure.\r
-  @param NewVariable             Pointer to new variable.\r
-  @param NewVariableSize         New variable size.\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_OUT_OF_RESOURCES\r
-  @return EFI_SUCCESS\r
-  @return Others\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
+  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
@@ -863,7 +1058,7 @@ Reclaim (
 \r
   //\r
   // Reinstall all ADDED variables as long as they are not identical to Updating Variable.\r
-  // \r
+  //\r
   Variable = GetStartPointer (VariableStoreHeader);\r
   while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {\r
     NextVariable = GetNextVariablePtr (Variable);\r
@@ -885,24 +1080,24 @@ Reclaim (
 \r
   //\r
   // Reinstall all in delete transition variables.\r
-  // \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
+      // 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
+      // no ADDED one in previous buffer.\r
+      //\r
+\r
       FoundAdded = FALSE;\r
       AddedVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer);\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
@@ -1033,14 +1228,14 @@ Done:
 /**\r
   Find the variable in the specified variable store.\r
 \r
-  @param  VariableName        Name of the variable to be found\r
-  @param  VendorGuid          Vendor GUID to be found.\r
-  @param  IgnoreRtCheck       Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute\r
-                              check at runtime when searching variable.\r
-  @param  PtrTrack            Variable Track Pointer structure that contains Variable Information.\r
+  @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
+  @retval          EFI_SUCCESS         Variable found successfully\r
+  @retval          EFI_NOT_FOUND       Variable not found\r
 **/\r
 EFI_STATUS\r
 FindVariableEx (\r
@@ -1064,7 +1259,7 @@ FindVariableEx (
       ; IsValidVariableHeader (PtrTrack->CurrPtr, PtrTrack->EndPtr)\r
       ; PtrTrack->CurrPtr = GetNextVariablePtr (PtrTrack->CurrPtr)\r
       ) {\r
-    if (PtrTrack->CurrPtr->State == VAR_ADDED || \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
@@ -1076,7 +1271,7 @@ FindVariableEx (
             return EFI_SUCCESS;\r
           }\r
         } else {\r
-          if (CompareGuid (VendorGuid, &PtrTrack->CurrPtr->VendorGuid)) {\r
+          if (CompareGuid (VendorGuid, GetVendorGuidPtr (PtrTrack->CurrPtr))) {\r
             Point = (VOID *) GetVariableNamePtr (PtrTrack->CurrPtr);\r
 \r
             ASSERT (NameSizeOfVariable (PtrTrack->CurrPtr) != 0);\r
@@ -1109,14 +1304,14 @@ FindVariableEx (
   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  IgnoreRtCheck               Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute\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
@@ -1202,7 +1397,7 @@ GetIndexFromSupportedLangCodes(
   IN  CHAR8            *SupportedLang,\r
   IN  CHAR8            *Lang,\r
   IN  BOOLEAN          Iso639Language\r
-  ) \r
+  )\r
 {\r
   UINTN    Index;\r
   UINTN    CompareLength;\r
@@ -1237,8 +1432,8 @@ GetIndexFromSupportedLangCodes(
       // 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
+\r
+      if ((CompareLength == LanguageLength) &&\r
           (AsciiStrnCmp (Lang, SupportedLang, CompareLength) == 0)) {\r
         //\r
         // Successfully find the index of Lang string in SupportedLang string.\r
@@ -1336,10 +1531,10 @@ GetLangFromSupportedLangCodes (
 }\r
 \r
 /**\r
-  Returns a pointer to an allocated buffer that contains the best matching language \r
-  from a set of supported languages.  \r
-  \r
-  This function supports both ISO 639-2 and RFC 4646 language codes, but language \r
+  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
@@ -1347,37 +1542,37 @@ GetLangFromSupportedLangCodes (
   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
+                                  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
+  @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
+                                  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
+                                  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
+                                  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
+  @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
+  @retval Other  A pointer to a Null-terminated ASCII string that is the best matching\r
                  language in SupportedLanguages.\r
 \r
 **/\r
 CHAR8 *\r
 EFIAPI\r
 VariableGetBestLanguage (\r
-  IN CONST CHAR8  *SupportedLanguages, \r
+  IN CONST CHAR8  *SupportedLanguages,\r
   IN BOOLEAN      Iso639Language,\r
   ...\r
   )\r
@@ -1389,7 +1584,9 @@ VariableGetBestLanguage (
   CONST CHAR8  *Supported;\r
   CHAR8        *Buffer;\r
 \r
-  ASSERT (SupportedLanguages != NULL);\r
+  if (SupportedLanguages == NULL) {\r
+    return NULL;\r
+  }\r
 \r
   VA_START (Args, Iso639Language);\r
   while ((Language = VA_ARG (Args, CHAR8 *)) != NULL) {\r
@@ -1452,7 +1649,7 @@ VariableGetBestLanguage (
         LanguageLength = 0;\r
       } else {\r
         //\r
-        // If RFC 4646 mode, then trim Language from the right to the next '-' character \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
@@ -1461,7 +1658,7 @@ VariableGetBestLanguage (
   VA_END (Args);\r
 \r
   //\r
-  // No matches were found \r
+  // No matches were found\r
   //\r
   return NULL;\r
 }\r
@@ -1476,8 +1673,9 @@ VariableGetBestLanguage (
   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
+  @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
@@ -1487,9 +1685,9 @@ VariableGetBestLanguage (
 **/\r
 BOOLEAN\r
 EFIAPI\r
-CheckRemainingSpaceForConsistency (\r
+CheckRemainingSpaceForConsistencyInternal (\r
   IN UINT32                     Attributes,\r
-  ...\r
+  IN VA_LIST                    Marker\r
   )\r
 {\r
   EFI_STATUS                    Status;\r
@@ -1520,7 +1718,7 @@ CheckRemainingSpaceForConsistency (
   ASSERT_EFI_ERROR (Status);\r
 \r
   TotalNeededSize = 0;\r
-  VA_START (Args, Attributes);\r
+  Args = Marker;\r
   VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);\r
   while (VariableEntry != NULL) {\r
     //\r
@@ -1530,12 +1728,11 @@ CheckRemainingSpaceForConsistency (
     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
+    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
@@ -1550,7 +1747,7 @@ CheckRemainingSpaceForConsistency (
     return FALSE;\r
   }\r
 \r
-  VA_START (Args, Attributes);\r
+  Args = Marker;\r
   VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);\r
   while (VariableEntry != NULL) {\r
     //\r
@@ -1580,7 +1777,6 @@ CheckRemainingSpaceForConsistency (
       //\r
       // No enough space for Variable[Index].\r
       //\r
-      VA_END (Args);\r
       return FALSE;\r
     }\r
     //\r
@@ -1589,11 +1785,48 @@ CheckRemainingSpaceForConsistency (
     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
@@ -1660,7 +1893,7 @@ AutoUpdateLangVariable (
     ASSERT (mVariableModuleGlobal->PlatformLangCodes != NULL);\r
 \r
     //\r
-    // PlatformLang holds a single language from PlatformLangCodes, \r
+    // PlatformLang holds a single language from PlatformLangCodes,\r
     // so the size of PlatformLangCodes is enough for the PlatformLang.\r
     //\r
     if (mVariableModuleGlobal->PlatformLang != NULL) {\r
@@ -1690,7 +1923,7 @@ AutoUpdateLangVariable (
     ASSERT (mVariableModuleGlobal->LangCodes != NULL);\r
   }\r
 \r
-  if (SetLanguageCodes \r
+  if (SetLanguageCodes\r
       && (mVariableModuleGlobal->PlatformLangCodes != NULL)\r
       && (mVariableModuleGlobal->LangCodes != NULL)) {\r
     //\r
@@ -1704,7 +1937,7 @@ AutoUpdateLangVariable (
       //\r
       VariableName = EFI_PLATFORM_LANG_VARIABLE_NAME;\r
       Data         = GetVariableDataPtr (Variable.CurrPtr);\r
-      DataSize     = Variable.CurrPtr->DataSize;\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
@@ -1713,7 +1946,7 @@ AutoUpdateLangVariable (
         //\r
         VariableName = EFI_LANG_VARIABLE_NAME;\r
         Data         = GetVariableDataPtr (Variable.CurrPtr);\r
-        DataSize     = Variable.CurrPtr->DataSize;\r
+        DataSize     = DataSizeOfVariable (Variable.CurrPtr);\r
       } else {\r
         //\r
         // Neither PlatformLang nor Lang is set, directly return\r
@@ -1756,7 +1989,7 @@ AutoUpdateLangVariable (
         VariableEntry[0].VariableSize = ISO_639_2_ENTRY_SIZE + 1;\r
         VariableEntry[0].Guid = &gEfiGlobalVariableGuid;\r
         VariableEntry[0].Name = EFI_LANG_VARIABLE_NAME;\r
-        \r
+\r
         VariableEntry[1].VariableSize = AsciiStrSize (BestPlatformLang);\r
         VariableEntry[1].Guid = &gEfiGlobalVariableGuid;\r
         VariableEntry[1].Name = EFI_PLATFORM_LANG_VARIABLE_NAME;\r
@@ -1772,7 +2005,7 @@ AutoUpdateLangVariable (
           FindVariable (EFI_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
 \r
           Status = UpdateVariable (EFI_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, BestLang,\r
-                                   ISO_639_2_ENTRY_SIZE + 1, Attributes, &Variable);\r
+                                   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
@@ -1820,8 +2053,8 @@ AutoUpdateLangVariable (
           //\r
           FindVariable (EFI_PLATFORM_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
 \r
-          Status = UpdateVariable (EFI_PLATFORM_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, BestPlatformLang, \r
-                                   AsciiStrSize (BestPlatformLang), Attributes, &Variable);\r
+          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 Status: %r\n", BestLang, BestPlatformLang, Status));\r
@@ -1840,16 +2073,51 @@ AutoUpdateLangVariable (
 }\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
+\r
+  @param FirstTime           A pointer to the first EFI_TIME data.\r
+  @param SecondTime          A pointer to the second EFI_TIME data.\r
+\r
+  @retval  TRUE              The FirstTime is not later than the SecondTime.\r
+  @retval  FALSE             The FirstTime is later than the SecondTime.\r
+\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
+  return (BOOLEAN) (FirstTime->Second <= SecondTime->Second);\r
+}\r
+\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         Attribues of the variable.\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
-  \r
+  @param[in] TimeStamp          Value of associated TimeStamp.\r
+\r
   @retval EFI_SUCCESS           The update operation is success.\r
   @retval EFI_OUT_OF_RESOURCES  Variable region is full, can not write other data into this region.\r
 \r
@@ -1861,12 +2129,16 @@ UpdateVariable (
   IN      VOID                        *Data,\r
   IN      UINTN                       DataSize,\r
   IN      UINT32                      Attributes      OPTIONAL,\r
-  IN OUT  VARIABLE_POINTER_TRACK      *CacheVariable\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                               MaxDataSize;\r
   UINTN                               VarNameOffset;\r
   UINTN                               VarDataOffset;\r
   UINTN                               VarNameSize;\r
@@ -1878,15 +2150,32 @@ UpdateVariable (
   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) && ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0)) {\r
+  if (mVariableModuleGlobal->FvbInstance == NULL) {\r
     //\r
-    // The FVB protocol is not ready. Trying to update NV variable prior to the installation\r
-    // of EFI_VARIABLE_WRITE_ARCH_PROTOCOL.\r
+    // The FVB protocol is not ready, so the EFI_VARIABLE_WRITE_ARCH_PROTOCOL is not installed.\r
     //\r
-    return EFI_NOT_AVAILABLE_YET;     \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
   if ((CacheVariable->CurrPtr == NULL) || CacheVariable->Volatile) {\r
@@ -1898,7 +2187,7 @@ UpdateVariable (
     // 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 = &NvVariable;\r
     Variable->StartPtr = GetStartPointer (VariableStoreHeader);\r
     Variable->EndPtr   = GetEndPointer (VariableStoreHeader);\r
     Variable->CurrPtr  = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->CurrPtr - (UINTN)CacheVariable->StartPtr));\r
@@ -1908,18 +2197,27 @@ UpdateVariable (
       Variable->InDeletedTransitionPtr = NULL;\r
     }\r
     Variable->Volatile = FALSE;\r
-  } \r
+  }\r
 \r
   Fvb       = mVariableModuleGlobal->FvbInstance;\r
 \r
+  //\r
+  // Tricky part: Use scratch data area at the end of volatile variable store\r
+  // as a temporary storage.\r
+  //\r
+  NextVariable = GetEndPointer ((VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase));\r
+  ScratchSize = mVariableModuleGlobal->ScratchBufferSize;\r
+  SetMem (NextVariable, ScratchSize, 0xff);\r
+  DataReady = FALSE;\r
+\r
   if (Variable->CurrPtr != NULL) {\r
     //\r
     // Update/Delete existing variable.\r
     //\r
-    if (AtRuntime ()) {        \r
+    if (AtRuntime ()) {\r
       //\r
-      // If AtRuntime 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
@@ -1927,19 +2225,29 @@ UpdateVariable (
         goto Done;\r
       }\r
       //\r
-      // Only variable that have NV|RT attributes can be updated/deleted in Runtime.\r
+      // Only variable that have NV attributes can be updated/deleted in Runtime.\r
       //\r
-      if (((Variable->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) || ((Variable->CurrPtr->Attributes & EFI_VARIABLE_NON_VOLATILE) == 0)) {\r
+      if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {\r
         Status = EFI_INVALID_PARAMETER;\r
-        goto Done;      \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_RUNTIME_ACCESS) == 0) {\r
+        Status = EFI_INVALID_PARAMETER;\r
+        goto Done;\r
       }\r
     }\r
 \r
     //\r
     // Setting a data variable with no access, or zero DataSize attributes\r
     // 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
+    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
@@ -1977,7 +2285,7 @@ UpdateVariable (
                  (UINTN) &Variable->CurrPtr->State,\r
                  sizeof (UINT8),\r
                  &State\r
-                 ); \r
+                 );\r
       if (!EFI_ERROR (Status)) {\r
         UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, FALSE, TRUE, FALSE);\r
         if (!Variable->Volatile) {\r
@@ -1985,21 +2293,72 @@ UpdateVariable (
           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
     // then return to the caller immediately.\r
     //\r
     if (DataSizeOfVariable (Variable->CurrPtr) == DataSize &&\r
-        (CompareMem (Data, GetVariableDataPtr (Variable->CurrPtr), DataSize) == 0)) {\r
-      \r
+        (CompareMem (Data, GetVariableDataPtr (Variable->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
 \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 (Variable->CurrPtr);\r
+        BufferForMerge = (UINT8 *) ((UINTN) NextVariable + DataOffset);\r
+        CopyMem (BufferForMerge, (UINT8 *) ((UINTN) Variable->CurrPtr + DataOffset), DataSizeOfVariable (Variable->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 (Variable->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 (Variable->CurrPtr)), Data, DataSize);\r
+        MergedBufSize = DataSizeOfVariable (Variable->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
       //\r
@@ -2014,28 +2373,33 @@ UpdateVariable (
                  (UINTN) &Variable->CurrPtr->State,\r
                  sizeof (UINT8),\r
                  &State\r
-                 );      \r
+                 );\r
       if (EFI_ERROR (Status)) {\r
-        goto Done;  \r
-      } \r
+        goto Done;\r
+      }\r
       if (!Variable->Volatile) {\r
         CacheVariable->CurrPtr->State = State;\r
       }\r
-    }    \r
+    }\r
   } else {\r
     //\r
     // Not found existing variable. Create a new variable.\r
-    //  \r
-    \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 zero DataSize or no access 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
     //\r
@@ -2043,29 +2407,50 @@ UpdateVariable (
         (((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
   //\r
-  // Tricky part: Use scratch data area at the end of volatile variable store\r
-  // as a temporary storage.\r
-  //\r
-  NextVariable = GetEndPointer ((VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase));\r
-  ScratchSize = MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize));\r
-\r
-  SetMem (NextVariable, 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
+  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 *) Variable->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
@@ -2073,19 +2458,27 @@ UpdateVariable (
     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
   //\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
@@ -2122,8 +2515,14 @@ UpdateVariable (
       //\r
       // Perform garbage collection & reclaim operation, and integrate the new variable at the same time.\r
       //\r
-      Status = Reclaim (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase, \r
-                        &mVariableModuleGlobal->NonVolatileLastVariableOffset, FALSE, Variable, NextVariable, HEADER_ALIGN (VarSize));\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
@@ -2147,7 +2546,7 @@ UpdateVariable (
     //\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
@@ -2161,7 +2560,7 @@ UpdateVariable (
                TRUE,\r
                Fvb,\r
                mVariableModuleGlobal->NonVolatileLastVariableOffset,\r
-               sizeof (VARIABLE_HEADER),\r
+               (UINT32) GetVariableHeaderSize (),\r
                (UINT8 *) NextVariable\r
                );\r
 \r
@@ -2194,9 +2593,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
@@ -2237,7 +2636,7 @@ UpdateVariable (
   } else {\r
     //\r
     // Create a volatile variable.\r
-    //      \r
+    //\r
     Volatile = TRUE;\r
 \r
     if ((UINT32) (VarSize + mVariableModuleGlobal->VolatileLastVariableOffset) >\r
@@ -2245,8 +2644,14 @@ UpdateVariable (
       //\r
       // Perform garbage collection & reclaim operation, and integrate the new variable at the same time.\r
       //\r
-      Status = Reclaim (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase, \r
-                          &mVariableModuleGlobal->VolatileLastVariableOffset, TRUE, Variable, NextVariable, HEADER_ALIGN (VarSize));\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
@@ -2320,7 +2725,7 @@ UpdateVariable (
              sizeof (UINT8),\r
              &State\r
              );\r
-    if (!EFI_ERROR (Status) && !Variable->Volatile) {         \r
+    if (!EFI_ERROR (Status) && !Variable->Volatile) {\r
       CacheVariable->CurrPtr->State = State;\r
     }\r
   }\r
@@ -2339,8 +2744,8 @@ Done:
 /**\r
   Check if a Unicode character is a hexadecimal character.\r
 \r
-  This function checks if a Unicode character is a \r
-  hexadecimal character.  The valid hexadecimal character is \r
+  This function checks if a Unicode character is a\r
+  hexadecimal character.  The valid hexadecimal character is\r
   L'0' to L'9', L'a' to L'f', or L'A' to L'F'.\r
 \r
 \r
@@ -2396,6 +2801,7 @@ IsHwErrRecVariable (
 /**\r
   Mark a variable that will become read-only after leaving the DXE phase of execution.\r
 \r
+\r
   @param[in] This          The VARIABLE_LOCK_PROTOCOL instance.\r
   @param[in] VariableName  A pointer to the variable name that will be made read-only subsequently.\r
   @param[in] VendorGuid    A pointer to the vendor GUID that will be made read-only subsequently.\r
@@ -2418,6 +2824,8 @@ VariableLockRequestToLock (
 {\r
   VARIABLE_ENTRY                  *Entry;\r
   CHAR16                          *Name;\r
+  LIST_ENTRY                      *Link;\r
+  VARIABLE_ENTRY                  *LockedEntry;\r
 \r
   if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {\r
     return EFI_INVALID_PARAMETER;\r
@@ -2436,11 +2844,23 @@ VariableLockRequestToLock (
 \r
   AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
 \r
+  for ( Link = GetFirstNode (&mLockedVariableList)\r
+      ; !IsNull (&mLockedVariableList, Link)\r
+      ; Link = GetNextNode (&mLockedVariableList, Link)\r
+      ) {\r
+    LockedEntry = BASE_CR (Link, VARIABLE_ENTRY, Link);\r
+    Name = (CHAR16 *) ((UINTN) LockedEntry + sizeof (*LockedEntry));\r
+    if (CompareGuid (&LockedEntry->Guid, VendorGuid) && (StrCmp (Name, VariableName) == 0)) {\r
+      goto Done;\r
+    }\r
+  }\r
+\r
   Name = (CHAR16 *) ((UINTN) Entry + sizeof (*Entry));\r
-  StrnCpy   (Name, VariableName, StrLen (VariableName));\r
+  StrCpyS (Name, StrSize (VariableName)/sizeof(CHAR16), VariableName);\r
   CopyGuid (&Entry->Guid, VendorGuid);\r
   InsertTailList (&mLockedVariableList, &Entry->Link);\r
 \r
+Done:\r
   ReleaseLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
 \r
   return EFI_SUCCESS;\r
@@ -2460,7 +2880,7 @@ VariableLockRequestToLock (
   @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
+\r
   @return EFI_INVALID_PARAMETER     Invalid parameter.\r
   @return EFI_SUCCESS               Find the specified variable.\r
   @return EFI_NOT_FOUND             Not found.\r
@@ -2486,7 +2906,7 @@ VariableServiceGetVariable (
   }\r
 \r
   AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
-  \r
+\r
   Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
   if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {\r
     goto Done;\r
@@ -2511,7 +2931,7 @@ VariableServiceGetVariable (
 \r
     *DataSize = VarDataSize;\r
     UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE);\r
\r
+\r
     Status = EFI_SUCCESS;\r
     goto Done;\r
   } else {\r
@@ -2525,47 +2945,35 @@ Done:
   return Status;\r
 }\r
 \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           Size of the variable name.\r
-  @param VariableName               Pointer to variable name.\r
-  @param VendorGuid                 Variable Vendor Guid.\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
+  @return EFI_SUCCESS       Find the specified variable.\r
+  @return EFI_NOT_FOUND     Not found.\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
+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
   VARIABLE_POINTER_TRACK  VariableInHob;\r
   VARIABLE_POINTER_TRACK  VariablePtrTrack;\r
-  UINTN                   VarNameSize;\r
   EFI_STATUS              Status;\r
   VARIABLE_STORE_HEADER   *VariableStoreHeader[VariableStoreTypeMax];\r
 \r
-  if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {\r
-    return EFI_INVALID_PARAMETER;\r
-  }\r
-\r
-  AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
-\r
   Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);\r
   if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {\r
     goto Done;\r
@@ -2610,7 +3018,7 @@ VariableServiceGetNextVariableName (
         }\r
       }\r
       //\r
-      // Capture the case that \r
+      // Capture the case that\r
       // 1. current storage is the last one, or\r
       // 2. no further storage\r
       //\r
@@ -2638,7 +3046,7 @@ VariableServiceGetNextVariableName (
           VariablePtrTrack.EndPtr = Variable.EndPtr;\r
           Status = FindVariableEx (\r
                      GetVariableNamePtr (Variable.CurrPtr),\r
-                     &Variable.CurrPtr->VendorGuid,\r
+                     GetVendorGuidPtr (Variable.CurrPtr),\r
                      FALSE,\r
                      &VariablePtrTrack\r
                      );\r
@@ -2651,14 +3059,14 @@ VariableServiceGetNextVariableName (
         //\r
         // Don't return NV variable when HOB overrides it\r
         //\r
-        if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) && \r
+        if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) &&\r
             (Variable.StartPtr == GetStartPointer (VariableStoreHeader[VariableStoreTypeNv]))\r
            ) {\r
           VariableInHob.StartPtr = GetStartPointer (VariableStoreHeader[VariableStoreTypeHob]);\r
           VariableInHob.EndPtr   = GetEndPointer   (VariableStoreHeader[VariableStoreTypeHob]);\r
           Status = FindVariableEx (\r
                      GetVariableNamePtr (Variable.CurrPtr),\r
-                     &Variable.CurrPtr->VendorGuid,\r
+                     GetVendorGuidPtr (Variable.CurrPtr),\r
                      FALSE,\r
                      &VariableInHob\r
                      );\r
@@ -2668,18 +3076,8 @@ VariableServiceGetNextVariableName (
           }\r
         }\r
 \r
-        VarNameSize = NameSizeOfVariable (Variable.CurrPtr);\r
-        ASSERT (VarNameSize != 0);\r
-\r
-        if (VarNameSize <= *VariableNameSize) {\r
-          CopyMem (VariableName, GetVariableNamePtr (Variable.CurrPtr), VarNameSize);\r
-          CopyMem (VendorGuid, &Variable.CurrPtr->VendorGuid, sizeof (EFI_GUID));\r
-          Status = EFI_SUCCESS;\r
-        } else {\r
-          Status = EFI_BUFFER_TOO_SMALL;\r
-        }\r
-\r
-        *VariableNameSize = VarNameSize;\r
+        *VariablePtr = Variable.CurrPtr;\r
+        Status = EFI_SUCCESS;\r
         goto Done;\r
       }\r
     }\r
@@ -2688,6 +3086,59 @@ VariableServiceGetNextVariableName (
   }\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           Size of the variable name.\r
+  @param VariableName               Pointer to variable name.\r
+  @param VendorGuid                 Variable Vendor Guid.\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
+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                   VarNameSize;\r
+  VARIABLE_HEADER         *VariablePtr;\r
+\r
+  if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {\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
@@ -2699,6 +3150,9 @@ Done:
   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
@@ -2728,6 +3182,7 @@ VariableServiceSetVariable (
   EFI_STATUS                          Status;\r
   VARIABLE_HEADER                     *NextVariable;\r
   EFI_PHYSICAL_ADDRESS                Point;\r
+  UINTN                               PayloadSize;\r
   LIST_ENTRY                          *Link;\r
   VARIABLE_ENTRY                      *Entry;\r
   CHAR16                              *Name;\r
@@ -2737,16 +3192,16 @@ VariableServiceSetVariable (
   //\r
   if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {\r
     return EFI_INVALID_PARAMETER;\r
-  } \r
+  }\r
 \r
   if (DataSize != 0 && Data == NULL) {\r
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
   //\r
-  // Not support authenticated or append variable write yet.\r
+  // Check for reserverd bit in variable attribute.\r
   //\r
-  if ((Attributes & (EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_APPEND_WRITE)) != 0) {\r
+  if ((Attributes & (~EFI_VARIABLE_ATTRIBUTES_MASK)) != 0) {\r
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
@@ -2755,22 +3210,67 @@ VariableServiceSetVariable (
   //\r
   if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {\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_INVALID_PARAMETER;\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_INVALID_PARAMETER;\r
+    }\r
+  }\r
+\r
+  //\r
+  // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS and EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute\r
+  // cannot be set both.\r
+  //\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_INVALID_PARAMETER;\r
+  }\r
+\r
+  if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) {\r
+    if (DataSize < AUTHINFO_SIZE) {\r
+      //\r
+      // Try to write Authenticated Variable without AuthInfo.\r
+      //\r
+      return EFI_SECURITY_VIOLATION;\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) - DataSize < StrSize(VariableName)){\r
+  if ((UINTN)(~0) - PayloadSize < StrSize(VariableName)){\r
+    //\r
+    // Prevent whole variable size overflow\r
     //\r
-    // Prevent whole variable size overflow \r
-    // \r
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
   //\r
   //  The size of the VariableName, including the Unicode Null in bytes plus\r
   //  the DataSize is limited to maximum size of PcdGet32 (PcdMaxHardwareErrorVariableSize)\r
-  //  bytes for HwErrRec, and PcdGet32 (PcdMaxVariableSize) bytes for the others.\r
+  //  bytes for HwErrRec#### variable.\r
   //\r
   if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {\r
-    if ( StrSize (VariableName) + DataSize > PcdGet32 (PcdMaxHardwareErrorVariableSize) - sizeof (VARIABLE_HEADER)) {\r
+    if (StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxHardwareErrorVariableSize) - GetVariableHeaderSize ()) {\r
       return EFI_INVALID_PARAMETER;\r
     }\r
     if (!IsHwErrRecVariable(VariableName, VendorGuid)) {\r
@@ -2779,13 +3279,24 @@ VariableServiceSetVariable (
   } else {\r
     //\r
     //  The size of the VariableName, including the Unicode Null in bytes plus\r
-    //  the DataSize is limited to maximum size of PcdGet32 (PcdMaxVariableSize) bytes.\r
+    //  the DataSize is limited to maximum size of Max(Auth)VariableSize bytes.\r
     //\r
-    if (StrSize (VariableName) + DataSize > PcdGet32 (PcdMaxVariableSize) - sizeof (VARIABLE_HEADER)) {\r
-      return EFI_INVALID_PARAMETER;\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
+  Status = InternalVarCheckSetVariableCheck (VariableName, VendorGuid, Attributes, PayloadSize, (VOID *) ((UINTN) Data + DataSize - PayloadSize));\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+\r
   AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
 \r
   //\r
@@ -2821,11 +3332,6 @@ VariableServiceSetVariable (
     }\r
   }\r
 \r
-  Status = InternalVarCheckSetVariableCheck (VariableName, VendorGuid, Attributes, DataSize, Data);\r
-  if (EFI_ERROR (Status)) {\r
-    goto Done;\r
-  }\r
-\r
   //\r
   // Check whether the input variable is already existed.\r
   //\r
@@ -2835,7 +3341,7 @@ VariableServiceSetVariable (
       Status = EFI_WRITE_PROTECTED;\r
       goto Done;\r
     }\r
-    if (Attributes != 0 && Attributes != Variable.CurrPtr->Attributes) {\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
@@ -2861,12 +3367,25 @@ VariableServiceSetVariable (
     }\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
@@ -2933,7 +3452,7 @@ VariableServiceQueryVariableInfoInternal (
   //\r
   if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {\r
     *MaximumVariableStorageSize = PcdGet32 (PcdHwErrStorageSize);\r
-    *MaximumVariableSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - sizeof (VARIABLE_HEADER);\r
+    *MaximumVariableSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - GetVariableHeaderSize ();\r
   } else {\r
     if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {\r
       if (AtRuntime ()) {\r
@@ -2944,9 +3463,13 @@ VariableServiceQueryVariableInfoInternal (
     }\r
 \r
     //\r
-    // Let *MaximumVariableSize be PcdGet32 (PcdMaxVariableSize) with the exception of the variable header size.\r
+    // Let *MaximumVariableSize be Max(Auth)VariableSize with the exception of the variable header size.\r
     //\r
-    *MaximumVariableSize = PcdGet32 (PcdMaxVariableSize) - sizeof (VARIABLE_HEADER);\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
@@ -2994,7 +3517,7 @@ VariableServiceQueryVariableInfoInternal (
         VariablePtrTrack.EndPtr   = GetEndPointer   (VariableStoreHeader);\r
         Status = FindVariableEx (\r
                    GetVariableNamePtr (Variable),\r
-                   &Variable->VendorGuid,\r
+                   GetVendorGuidPtr (Variable),\r
                    FALSE,\r
                    &VariablePtrTrack\r
                    );\r
@@ -3024,10 +3547,10 @@ VariableServiceQueryVariableInfoInternal (
     }\r
   }\r
 \r
-  if (*RemainingVariableStorageSize < sizeof (VARIABLE_HEADER)) {\r
+  if (*RemainingVariableStorageSize < GetVariableHeaderSize ()) {\r
     *MaximumVariableSize = 0;\r
-  } else if ((*RemainingVariableStorageSize - sizeof (VARIABLE_HEADER)) < *MaximumVariableSize) {\r
-    *MaximumVariableSize = *RemainingVariableStorageSize - sizeof (VARIABLE_HEADER);\r
+  } else if ((*RemainingVariableStorageSize - GetVariableHeaderSize ()) < *MaximumVariableSize) {\r
+    *MaximumVariableSize = *RemainingVariableStorageSize - GetVariableHeaderSize ();\r
   }\r
 \r
   return EFI_SUCCESS;\r
@@ -3069,7 +3592,7 @@ VariableServiceQueryVariableInfo (
     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_ATTRIBUTES_MASK) == 0) {\r
     //\r
     // Make sure the Attributes combination is supported by the platform.\r
     //\r
@@ -3089,11 +3612,20 @@ VariableServiceQueryVariableInfo (
     // Make sure Hw Attribute is set with NV.\r
     //\r
     return EFI_INVALID_PARAMETER;\r
-  } else if ((Attributes & (EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_APPEND_WRITE)) != 0) {\r
-    //\r
-    // Not support authenticated or append variable write yet.\r
-    //\r
-    return EFI_UNSUPPORTED;\r
+  } 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
@@ -3124,6 +3656,15 @@ ReclaimForOS(
   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
@@ -3134,11 +3675,13 @@ ReclaimForOS(
   }\r
 \r
   RemainingHwErrVariableSpace = PcdGet32 (PcdHwErrStorageSize) - mVariableModuleGlobal->HwErrVariableTotalSize;\r
+\r
   //\r
   // Check if the free area is below a threshold.\r
   //\r
-  if ((RemainingCommonRuntimeVariableSpace < PcdGet32 (PcdMaxVariableSize))\r
-    || ((PcdGet32 (PcdHwErrStorageSize) != 0) &&\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
@@ -3152,9 +3695,30 @@ ReclaimForOS(
   }\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
@@ -3162,7 +3726,7 @@ ReclaimForOS(
 **/\r
 EFI_STATUS\r
 InitNonVolatileVariableStore (\r
-  VOID\r
+  OUT EFI_FIRMWARE_VOLUME_HEADER    **NvFvHeader\r
   )\r
 {\r
   EFI_FIRMWARE_VOLUME_HEADER            *FvHeader;\r
@@ -3218,7 +3782,7 @@ InitNonVolatileVariableStore (
     } 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
+      // Flash NV storage from the Offset is backed up in spare block.\r
       //\r
       BackUpOffset = (UINT32) (FtwLastWriteData->TargetAddress - NvStorageBase);\r
       BackUpSize = NvStorageSize - BackUpOffset;\r
@@ -3253,9 +3817,10 @@ InitNonVolatileVariableStore (
   }\r
   ASSERT(mNvVariableCache->Size == VariableStoreLength);\r
 \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
@@ -3264,17 +3829,17 @@ InitNonVolatileVariableStore (
   // 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
+  // (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
+  // (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
+  // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize).\r
   //\r
   ASSERT (BoottimeReservedNvVariableSpaceSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize));\r
 \r
@@ -3285,9 +3850,12 @@ InitNonVolatileVariableStore (
   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 variable or hardware error variable size should be < variable store size.\r
+  // The max NV variable size should be < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)).\r
   //\r
-  ASSERT(MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize)) < VariableStoreLength);\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
@@ -3306,6 +3874,7 @@ InitNonVolatileVariableStore (
   }\r
   mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) Variable - (UINTN) VariableStoreBase;\r
 \r
+  *NvFvHeader = FvHeader;\r
   return EFI_SUCCESS;\r
 }\r
 \r
@@ -3351,17 +3920,17 @@ FlushHobVariableToFlash (
       }\r
       ASSERT ((Variable->Attributes & EFI_VARIABLE_NON_VOLATILE) != 0);\r
       if (VendorGuid == NULL || VariableName == NULL ||\r
-          !CompareGuid (VendorGuid, &Variable->VendorGuid) ||\r
+          !CompareGuid (VendorGuid, GetVendorGuidPtr (Variable)) ||\r
           StrCmp (VariableName, GetVariableNamePtr (Variable)) != 0) {\r
         VariableData = GetVariableDataPtr (Variable);\r
         Status = VariableServiceSetVariable (\r
                    GetVariableNamePtr (Variable),\r
-                   &Variable->VendorGuid,\r
+                   GetVendorGuidPtr (Variable),\r
                    Variable->Attributes,\r
-                   Variable->DataSize,\r
+                   DataSizeOfVariable (Variable),\r
                    VariableData\r
                    );\r
-        DEBUG ((EFI_D_INFO, "Variable driver flush the HOB variable to flash: %g %s %r\n", &Variable->VendorGuid, GetVariableNamePtr (Variable), Status));\r
+        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 the HOB variable.\r
@@ -3375,7 +3944,7 @@ FlushHobVariableToFlash (
         // If set variable successful, or the updated or deleted variable is matched with the HOB variable,\r
         // set the HOB variable to DELETED state in local.\r
         //\r
-        DEBUG ((EFI_D_INFO, "Variable driver set the HOB variable to DELETED state in local: %g %s\n", &Variable->VendorGuid, GetVariableNamePtr (Variable)));\r
+        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
@@ -3417,6 +3986,7 @@ VariableWriteServiceInitialize (
   UINT8                           Data;\r
   EFI_PHYSICAL_ADDRESS            VariableStoreBase;\r
   EFI_PHYSICAL_ADDRESS            NvStorageBase;\r
+  VARIABLE_ENTRY_PROPERTY         *VariableEntry;\r
 \r
   NvStorageBase = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageVariableBase64);\r
   if (NvStorageBase == 0) {\r
@@ -3429,7 +3999,7 @@ VariableWriteServiceInitialize (
   //\r
   mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;\r
   VariableStoreHeader = (VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase;\r
\r
+\r
   //\r
   // Check if the free area is really free.\r
   //\r
@@ -3456,7 +4026,46 @@ VariableWriteServiceInitialize (
 \r
   FlushHobVariableToFlash (NULL, NULL);\r
 \r
-  return EFI_SUCCESS;\r
+  Status = EFI_SUCCESS;\r
+  ZeroMem (&mContextOut, sizeof (mContextOut));\r
+  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {\r
+    //\r
+    // Authenticated variable initialize.\r
+    //\r
+    mContextIn.StructSize = sizeof (AUTH_VAR_LIB_CONTEXT_IN);\r
+    mContextIn.MaxAuthVariableSize = mVariableModuleGlobal->MaxAuthVariableSize - GetVariableHeaderSize ();\r
+    Status = AuthVariableLibInitialize (&mContextIn, &mContextOut);\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 (mContextOut.AuthVarEntry != NULL) {\r
+        for (Index = 0; Index < mContextOut.AuthVarEntryCount; Index++) {\r
+          VariableEntry = &mContextOut.AuthVarEntry[Index];\r
+          Status = InternalVarCheckVariablePropertySet (\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 (!EFI_ERROR (Status)) {\r
+    for (Index = 0; Index < sizeof (mVariableEntryProperty) / sizeof (mVariableEntryProperty[0]); Index++) {\r
+      VariableEntry = &mVariableEntryProperty[Index];\r
+      Status = InternalVarCheckVariablePropertySet (VariableEntry->Name, VariableEntry->Guid, &VariableEntry->VariableProperty);\r
+      ASSERT_EFI_ERROR (Status);\r
+    }\r
+  }\r
+\r
+  return Status;\r
 }\r
 \r
 \r
@@ -3478,6 +4087,8 @@ VariableCommonInitialize (
   UINT64                          VariableStoreLength;\r
   UINTN                           ScratchSize;\r
   EFI_HOB_GUID_TYPE               *GuidHob;\r
+  EFI_GUID                        *VariableGuid;\r
+  EFI_FIRMWARE_VOLUME_HEADER      *NvFvHeader;\r
 \r
   //\r
   // Allocate runtime memory for variable driver global structure.\r
@@ -3489,16 +4100,44 @@ VariableCommonInitialize (
 \r
   InitializeLock (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock, TPL_NOTIFY);\r
 \r
+  //\r
+  // Init non-volatile variable store.\r
+  //\r
+  NvFvHeader = NULL;\r
+  Status = InitNonVolatileVariableStore (&NvFvHeader);\r
+  if (EFI_ERROR (Status)) {\r
+    FreePool (mVariableModuleGlobal);\r
+    return Status;\r
+  }\r
+\r
+  //\r
+  // mVariableModuleGlobal->VariableGlobal.AuthFormat\r
+  // has been initialized in InitNonVolatileVariableStore().\r
+  //\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
   //\r
   // Get HOB variable store.\r
   //\r
-  GuidHob = GetFirstGuidHob (&gEfiVariableGuid);\r
+  GuidHob = GetFirstGuidHob (VariableGuid);\r
   if (GuidHob != NULL) {\r
     VariableStoreHeader = GET_GUID_HOB_DATA (GuidHob);\r
     VariableStoreLength = (UINT64) (GuidHob->Header.HobLength - sizeof (EFI_HOB_GUID_TYPE));\r
     if (GetVariableStoreStatus (VariableStoreHeader) == EfiValid) {\r
       mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) AllocateRuntimeCopyPool ((UINTN) VariableStoreLength, (VOID *) VariableStoreHeader);\r
       if (mVariableModuleGlobal->VariableGlobal.HobVariableBase == 0) {\r
+        FreePool (NvFvHeader);\r
         FreePool (mVariableModuleGlobal);\r
         return EFI_OUT_OF_RESOURCES;\r
       }\r
@@ -3510,12 +4149,14 @@ VariableCommonInitialize (
   //\r
   // Allocate memory for volatile variable store, note that there is a scratch space to store scratch data.\r
   //\r
-  ScratchSize = MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize));\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
     return EFI_OUT_OF_RESOURCES;\r
   }\r
@@ -3528,33 +4169,21 @@ VariableCommonInitialize (
   mVariableModuleGlobal->VariableGlobal.VolatileVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VolatileVariableStore;\r
   mVariableModuleGlobal->VolatileLastVariableOffset = (UINTN) GetStartPointer (VolatileVariableStore) - (UINTN) VolatileVariableStore;\r
 \r
-  CopyGuid (&VolatileVariableStore->Signature, &gEfiVariableGuid);\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
-  //\r
-  // Init non-volatile variable store.\r
-  //\r
-  Status = InitNonVolatileVariableStore ();\r
-  if (EFI_ERROR (Status)) {\r
-    if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {\r
-      FreePool ((VOID *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase);\r
-    }\r
-    FreePool (mVariableModuleGlobal);\r
-    FreePool (VolatileVariableStore);\r
-  }\r
-\r
-  return Status;\r
+  return EFI_SUCCESS;\r
 }\r
 \r
 \r
 /**\r
   Get the proper fvb handle and/or fvb protocol by the given Flash address.\r
 \r
-  @param[in] Address        The Flash address.\r
+  @param[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
@@ -3577,7 +4206,6 @@ GetFvbInfoByAddress (
   UINTN                                   NumberOfBlocks;\r
 \r
   HandleBuffer = NULL;\r
-\r
   //\r
   // Get all FVB handles.\r
   //\r
@@ -3637,7 +4265,7 @@ GetFvbInfoByAddress (
   if (Fvb == NULL) {\r
     Status = EFI_NOT_FOUND;\r
   }\r
-  \r
-  return Status;  \r
+\r
+  return Status;\r
 }\r
 \r