]> git.proxmox.com Git - mirror_edk2.git/blobdiff - MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c
MdeModulePkg: Replace BSD License with BSD+Patent License
[mirror_edk2.git] / MdeModulePkg / Universal / Variable / RuntimeDxe / VariableSmm.c
index 4009fcb1712eaded50b18d740c91a814e19c46f6..ec463d063ea4e1d5e0eb2bb0db5fdf3d43ea3873 100644 (file)
@@ -1,7 +1,6 @@
 /** @file\r
-\r
-  The sample implementation for SMM variable protocol. And this driver \r
-  implements  an SMI handler to communicate with the DXE runtime driver \r
+  The sample implementation for SMM variable protocol. And this driver\r
+  implements an SMI handler to communicate with the DXE runtime driver\r
   to provide variable services.\r
 \r
   Caution: This module requires additional review when modified.\r
 \r
   SmmVariableHandler() will receive untrusted input and do basic validation.\r
 \r
-  Each sub function VariableServiceGetVariable(), VariableServiceGetNextVariableName(), \r
-  VariableServiceSetVariable(), VariableServiceQueryVariableInfo(), ReclaimForOS(), \r
+  Each sub function VariableServiceGetVariable(), VariableServiceGetNextVariableName(),\r
+  VariableServiceSetVariable(), VariableServiceQueryVariableInfo(), ReclaimForOS(),\r
   SmmVariableGetStatistics() should also do validation based on its own knowledge.\r
 \r
-Copyright (c) 2010 - 2013, 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
-\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
+Copyright (c) 2010 - 2019, Intel Corporation. All rights reserved.<BR>\r
+Copyright (c) 2018, Linaro, Ltd. All rights reserved.<BR>\r
+SPDX-License-Identifier: BSD-2-Clause-Patent\r
 \r
 **/\r
+\r
 #include <Protocol/SmmVariable.h>\r
 #include <Protocol/SmmFirmwareVolumeBlock.h>\r
 #include <Protocol/SmmFaultTolerantWrite.h>\r
-#include <Protocol/SmmAccess2.h>\r
-#include <Protocol/SmmEndOfDxe.h>\r
+#include <Protocol/MmEndOfDxe.h>\r
+#include <Protocol/SmmVarCheck.h>\r
 \r
-#include <Library/SmmServicesTableLib.h>\r
+#include <Library/MmServicesTableLib.h>\r
 \r
-#include <Guid/VariableFormat.h>\r
 #include <Guid/SmmVariableCommon.h>\r
 #include "Variable.h"\r
 \r
-EFI_SMRAM_DESCRIPTOR                                 *mSmramRanges;\r
-UINTN                                                mSmramRangeCount;\r
-\r
-extern VARIABLE_INFO_ENTRY                           *gVariableInfo;\r
-EFI_HANDLE                                           mSmmVariableHandle      = NULL;\r
-EFI_HANDLE                                           mVariableHandle         = NULL;\r
 BOOLEAN                                              mAtRuntime              = FALSE;\r
-EFI_GUID                                             mZeroGuid               = {0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0}};\r
 UINT8                                                *mVariableBufferPayload = NULL;\r
 UINTN                                                mVariableBufferPayloadSize;\r
-extern BOOLEAN                                       mEndOfDxe;\r
-extern BOOLEAN                                       mEnableLocking;\r
+\r
+/**\r
+  SecureBoot Hook for SetVariable.\r
+\r
+  @param[in] VariableName                 Name of Variable to be found.\r
+  @param[in] VendorGuid                   Variable vendor GUID.\r
+\r
+**/\r
+VOID\r
+EFIAPI\r
+SecureBootHook (\r
+  IN CHAR16                                 *VariableName,\r
+  IN EFI_GUID                               *VendorGuid\r
+  )\r
+{\r
+  return ;\r
+}\r
 \r
 /**\r
 \r
@@ -83,7 +85,7 @@ SmmVariableSetVariable (
   //\r
   // Disable write protection when the calling SetVariable() through EFI_SMM_VARIABLE_PROTOCOL.\r
   //\r
-  mEnableLocking = FALSE;\r
+  mRequestSource = VarCheckFromTrusted;\r
   Status         = VariableServiceSetVariable (\r
                      VariableName,\r
                      VendorGuid,\r
@@ -91,7 +93,7 @@ SmmVariableSetVariable (
                      DataSize,\r
                      Data\r
                      );\r
-  mEnableLocking = TRUE;\r
+  mRequestSource = VarCheckFromUntrusted;\r
   return Status;\r
 }\r
 \r
@@ -102,9 +104,13 @@ EFI_SMM_VARIABLE_PROTOCOL      gSmmVariable = {
   VariableServiceQueryVariableInfo\r
 };\r
 \r
+EDKII_SMM_VAR_CHECK_PROTOCOL mSmmVarCheck = { VarCheckRegisterSetVariableCheckHandler,\r
+                                              VarCheckVariablePropertySet,\r
+                                              VarCheckVariablePropertyGet };\r
+\r
 /**\r
   Return TRUE if ExitBootServices () has been called.\r
-  \r
+\r
   @retval TRUE If ExitBootServices () has been called.\r
 **/\r
 BOOLEAN\r
@@ -115,65 +121,11 @@ AtRuntime (
   return mAtRuntime;\r
 }\r
 \r
-/**\r
-  This function check if the address is in SMRAM.\r
-\r
-  @param Buffer  the buffer address to be checked.\r
-  @param Length  the buffer length to be checked.\r
-\r
-  @retval TRUE  this address is in SMRAM.\r
-  @retval FALSE this address is NOT in SMRAM.\r
-**/\r
-BOOLEAN\r
-InternalIsAddressInSmram (\r
-  IN EFI_PHYSICAL_ADDRESS  Buffer,\r
-  IN UINT64                Length\r
-  )\r
-{\r
-  UINTN  Index;\r
-\r
-  for (Index = 0; Index < mSmramRangeCount; Index ++) {\r
-    if (((Buffer >= mSmramRanges[Index].CpuStart) && (Buffer < mSmramRanges[Index].CpuStart + mSmramRanges[Index].PhysicalSize)) ||\r
-        ((mSmramRanges[Index].CpuStart >= Buffer) && (mSmramRanges[Index].CpuStart < Buffer + Length))) {\r
-      return TRUE;\r
-    }\r
-  }\r
-\r
-  return FALSE;\r
-}\r
-\r
-/**\r
-  This function check if the address refered by Buffer and Length is valid.\r
-\r
-  @param Buffer  the buffer address to be checked.\r
-  @param Length  the buffer length to be checked.\r
-\r
-  @retval TRUE  this address is valid.\r
-  @retval FALSE this address is NOT valid.\r
-**/\r
-BOOLEAN\r
-InternalIsAddressValid (\r
-  IN UINTN                 Buffer,\r
-  IN UINTN                 Length\r
-  )\r
-{\r
-  if (Buffer > (MAX_ADDRESS - Length)) {\r
-    //\r
-    // Overflow happen\r
-    //\r
-    return FALSE;\r
-  }\r
-  if (InternalIsAddressInSmram ((EFI_PHYSICAL_ADDRESS)Buffer, (UINT64)Length)) {\r
-    return FALSE;\r
-  }\r
-  return TRUE;\r
-}\r
-\r
 /**\r
   Initializes a basic mutual exclusion lock.\r
 \r
-  This function initializes a basic mutual exclusion lock to the released state \r
-  and returns the lock.  Each lock provides mutual exclusion access at its task \r
+  This function initializes a basic mutual exclusion lock to the released state\r
+  and returns the lock.  Each lock provides mutual exclusion access at its task\r
   priority level.  Since there is no preemption or multiprocessor support in EFI,\r
   acquiring the lock only consists of raising to the locks TPL.\r
   If Lock is NULL, then ASSERT().\r
@@ -236,7 +188,7 @@ ReleaseLockOnlyAtBootTime (
 }\r
 \r
 /**\r
-  Retrive the SMM Fault Tolerent Write protocol interface.\r
+  Retrieve the SMM Fault Tolerent Write protocol interface.\r
 \r
   @param[out] FtwProtocol       The interface of SMM Ftw protocol\r
 \r
@@ -255,9 +207,9 @@ GetFtwProtocol (
   //\r
   // Locate Smm Fault Tolerent Write protocol\r
   //\r
-  Status = gSmst->SmmLocateProtocol (\r
-                    &gEfiSmmFaultTolerantWriteProtocolGuid, \r
-                    NULL, \r
+  Status = gMmst->MmLocateProtocol (\r
+                    &gEfiSmmFaultTolerantWriteProtocolGuid,\r
+                    NULL,\r
                     FtwProtocol\r
                     );\r
   return Status;\r
@@ -265,7 +217,7 @@ GetFtwProtocol (
 \r
 \r
 /**\r
-  Retrive the SMM FVB protocol interface by HANDLE.\r
+  Retrieve the SMM FVB protocol interface by HANDLE.\r
 \r
   @param[in]  FvBlockHandle     The handle of SMM FVB protocol that provides services for\r
                                 reading, writing, and erasing the target block.\r
@@ -285,7 +237,7 @@ GetFvbByHandle (
   //\r
   // To get the SMM FVB protocol interface on the handle\r
   //\r
-  return gSmst->SmmHandleProtocol (\r
+  return gMmst->MmHandleProtocol (\r
                   FvBlockHandle,\r
                   &gEfiSmmFirmwareVolumeBlockProtocolGuid,\r
                   (VOID **) FvBlock\r
@@ -295,7 +247,7 @@ GetFvbByHandle (
 \r
 /**\r
   Function returns an array of handles that support the SMM FVB protocol\r
-  in a buffer allocated from pool. \r
+  in a buffer allocated from pool.\r
 \r
   @param[out]  NumberHandles    The number of handles returned in Buffer.\r
   @param[out]  Buffer           A pointer to the buffer to return the requested\r
@@ -324,7 +276,7 @@ GetFvbCountAndBuffer (
   BufferSize     = 0;\r
   *NumberHandles = 0;\r
   *Buffer        = NULL;\r
-  Status = gSmst->SmmLocateHandle (\r
+  Status = gMmst->MmLocateHandle (\r
                     ByProtocol,\r
                     &gEfiSmmFirmwareVolumeBlockProtocolGuid,\r
                     NULL,\r
@@ -340,7 +292,7 @@ GetFvbCountAndBuffer (
     return EFI_OUT_OF_RESOURCES;\r
   }\r
 \r
-  Status = gSmst->SmmLocateHandle (\r
+  Status = gMmst->MmLocateHandle (\r
                     ByProtocol,\r
                     &gEfiSmmFirmwareVolumeBlockProtocolGuid,\r
                     NULL,\r
@@ -366,16 +318,17 @@ GetFvbCountAndBuffer (
   InfoEntry and InfoSize are external input. Care must be taken to make sure not security issue at runtime.\r
 \r
   @param[in, out]  InfoEntry    A pointer to the buffer of variable information entry.\r
-                                On input, point to the variable information returned last time. if \r
+                                On input, point to the variable information returned last time. if\r
                                 InfoEntry->VendorGuid is zero, return the first information.\r
                                 On output, point to the next variable information.\r
   @param[in, out]  InfoSize     On input, the size of the variable information buffer.\r
                                 On output, the returned variable information size.\r
 \r
-  @retval EFI_SUCCESS          The variable information is found and returned successfully.\r
-  @retval EFI_UNSUPPORTED      No variable inoformation exists in variable driver. The \r
-                               PcdVariableCollectStatistics should be set TRUE to support it.\r
-  @retval EFI_BUFFER_TOO_SMALL The buffer is too small to hold the next variable information.\r
+  @retval EFI_SUCCESS           The variable information is found and returned successfully.\r
+  @retval EFI_UNSUPPORTED       No variable inoformation exists in variable driver. The\r
+                                PcdVariableCollectStatistics should be set TRUE to support it.\r
+  @retval EFI_BUFFER_TOO_SMALL  The buffer is too small to hold the next variable information.\r
+  @retval EFI_INVALID_PARAMETER Input parameter is invalid.\r
 \r
 **/\r
 EFI_STATUS\r
@@ -385,32 +338,43 @@ SmmVariableGetStatistics (
   )\r
 {\r
   VARIABLE_INFO_ENTRY                                  *VariableInfo;\r
-  UINTN                                                NameLength;\r
+  UINTN                                                NameSize;\r
   UINTN                                                StatisticsInfoSize;\r
   CHAR16                                               *InfoName;\r
+  UINTN                                                InfoNameMaxSize;\r
   EFI_GUID                                             VendorGuid;\r
 \r
-  ASSERT (InfoEntry != NULL);\r
-  VariableInfo = gVariableInfo; \r
+  if (InfoEntry == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  VariableInfo = gVariableInfo;\r
   if (VariableInfo == NULL) {\r
     return EFI_UNSUPPORTED;\r
   }\r
 \r
-  StatisticsInfoSize = sizeof (VARIABLE_INFO_ENTRY) + StrSize (VariableInfo->Name);\r
+  StatisticsInfoSize = sizeof (VARIABLE_INFO_ENTRY);\r
   if (*InfoSize < StatisticsInfoSize) {\r
     *InfoSize = StatisticsInfoSize;\r
     return EFI_BUFFER_TOO_SMALL;\r
   }\r
   InfoName = (CHAR16 *)(InfoEntry + 1);\r
+  InfoNameMaxSize = (*InfoSize - sizeof (VARIABLE_INFO_ENTRY));\r
 \r
   CopyGuid (&VendorGuid, &InfoEntry->VendorGuid);\r
 \r
-  if (CompareGuid (&VendorGuid, &mZeroGuid)) {\r
+  if (IsZeroGuid (&VendorGuid)) {\r
     //\r
     // Return the first variable info\r
     //\r
+    NameSize = StrSize (VariableInfo->Name);\r
+    StatisticsInfoSize = sizeof (VARIABLE_INFO_ENTRY) + NameSize;\r
+    if (*InfoSize < StatisticsInfoSize) {\r
+      *InfoSize = StatisticsInfoSize;\r
+      return EFI_BUFFER_TOO_SMALL;\r
+    }\r
     CopyMem (InfoEntry, VariableInfo, sizeof (VARIABLE_INFO_ENTRY));\r
-    CopyMem (InfoName, VariableInfo->Name, StrSize (VariableInfo->Name));\r
+    CopyMem (InfoName, VariableInfo->Name, NameSize);\r
     *InfoSize = StatisticsInfoSize;\r
     return EFI_SUCCESS;\r
   }\r
@@ -420,9 +384,9 @@ SmmVariableGetStatistics (
   //\r
   while (VariableInfo != NULL) {\r
     if (CompareGuid (&VariableInfo->VendorGuid, &VendorGuid)) {\r
-      NameLength = StrSize (VariableInfo->Name);\r
-      if (NameLength == StrSize (InfoName)) {\r
-        if (CompareMem (VariableInfo->Name, InfoName, NameLength) == 0) {\r
+      NameSize = StrSize (VariableInfo->Name);\r
+      if (NameSize <= InfoNameMaxSize) {\r
+        if (CompareMem (VariableInfo->Name, InfoName, NameSize) == 0) {\r
           //\r
           // Find the match one\r
           //\r
@@ -433,7 +397,7 @@ SmmVariableGetStatistics (
     }\r
     VariableInfo = VariableInfo->Next;\r
   };\r
-    \r
+\r
   if (VariableInfo == NULL) {\r
     *InfoSize = 0;\r
     return EFI_SUCCESS;\r
@@ -442,16 +406,17 @@ SmmVariableGetStatistics (
   //\r
   // Output the new variable info\r
   //\r
-  StatisticsInfoSize = sizeof (VARIABLE_INFO_ENTRY) + StrSize (VariableInfo->Name);\r
+  NameSize = StrSize (VariableInfo->Name);\r
+  StatisticsInfoSize = sizeof (VARIABLE_INFO_ENTRY) + NameSize;\r
   if (*InfoSize < StatisticsInfoSize) {\r
     *InfoSize = StatisticsInfoSize;\r
     return EFI_BUFFER_TOO_SMALL;\r
   }\r
 \r
   CopyMem (InfoEntry, VariableInfo, sizeof (VARIABLE_INFO_ENTRY));\r
-  CopyMem (InfoName, VariableInfo->Name, StrSize (VariableInfo->Name));\r
+  CopyMem (InfoName, VariableInfo->Name, NameSize);\r
   *InfoSize = StatisticsInfoSize;\r
-  \r
+\r
   return EFI_SUCCESS;\r
 }\r
 \r
@@ -463,8 +428,8 @@ SmmVariableGetStatistics (
 \r
   Caution: This function may receive untrusted input.\r
   This variable data and communicate buffer are external input, so this function will do basic validation.\r
-  Each sub function VariableServiceGetVariable(), VariableServiceGetNextVariableName(), \r
-  VariableServiceSetVariable(), VariableServiceQueryVariableInfo(), ReclaimForOS(), \r
+  Each sub function VariableServiceGetVariable(), VariableServiceGetNextVariableName(),\r
+  VariableServiceSetVariable(), VariableServiceQueryVariableInfo(), ReclaimForOS(),\r
   SmmVariableGetStatistics() should also do validation based on its own knowledge.\r
 \r
   @param[in]     DispatchHandle  The unique handle assigned to this handler by SmiHandlerRegister().\r
@@ -474,11 +439,11 @@ SmmVariableGetStatistics (
                                  be conveyed from a non-SMM environment into an SMM environment.\r
   @param[in, out] CommBufferSize The size of the CommBuffer.\r
 \r
-  @retval EFI_SUCCESS                         The interrupt was handled and quiesced. No other handlers \r
+  @retval EFI_SUCCESS                         The interrupt was handled and quiesced. No other handlers\r
                                               should still be called.\r
-  @retval EFI_WARN_INTERRUPT_SOURCE_QUIESCED  The interrupt has been quiesced but other handlers should \r
+  @retval EFI_WARN_INTERRUPT_SOURCE_QUIESCED  The interrupt has been quiesced but other handlers should\r
                                               still be called.\r
-  @retval EFI_WARN_INTERRUPT_SOURCE_PENDING   The interrupt is still pending and other handlers should still \r
+  @retval EFI_WARN_INTERRUPT_SOURCE_PENDING   The interrupt is still pending and other handlers should still\r
                                               be called.\r
   @retval EFI_INTERRUPT_PENDING               The interrupt could not be quiesced.\r
 **/\r
@@ -496,11 +461,14 @@ SmmVariableHandler (
   SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE         *SmmVariableHeader;\r
   SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME  *GetNextVariableName;\r
   SMM_VARIABLE_COMMUNICATE_QUERY_VARIABLE_INFO     *QueryVariableInfo;\r
+  SMM_VARIABLE_COMMUNICATE_GET_PAYLOAD_SIZE        *GetPayloadSize;\r
   VARIABLE_INFO_ENTRY                              *VariableInfo;\r
   SMM_VARIABLE_COMMUNICATE_LOCK_VARIABLE           *VariableToLock;\r
+  SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY *CommVariableProperty;\r
   UINTN                                            InfoSize;\r
   UINTN                                            NameBufferSize;\r
   UINTN                                            CommBufferPayloadSize;\r
+  UINTN                                            TempCommBufferSize;\r
 \r
   //\r
   // If input is invalid, stop processing this SMI\r
@@ -509,17 +477,19 @@ SmmVariableHandler (
     return EFI_SUCCESS;\r
   }\r
 \r
-  if (*CommBufferSize < SMM_VARIABLE_COMMUNICATE_HEADER_SIZE) {\r
+  TempCommBufferSize = *CommBufferSize;\r
+\r
+  if (TempCommBufferSize < SMM_VARIABLE_COMMUNICATE_HEADER_SIZE) {\r
     DEBUG ((EFI_D_ERROR, "SmmVariableHandler: SMM communication buffer size invalid!\n"));\r
     return EFI_SUCCESS;\r
   }\r
-  CommBufferPayloadSize = *CommBufferSize - SMM_VARIABLE_COMMUNICATE_HEADER_SIZE;\r
+  CommBufferPayloadSize = TempCommBufferSize - SMM_VARIABLE_COMMUNICATE_HEADER_SIZE;\r
   if (CommBufferPayloadSize > mVariableBufferPayloadSize) {\r
     DEBUG ((EFI_D_ERROR, "SmmVariableHandler: SMM communication buffer payload size invalid!\n"));\r
     return EFI_SUCCESS;\r
   }\r
 \r
-  if (!InternalIsAddressValid ((UINTN)CommBuffer, *CommBufferSize)) {\r
+  if (!VariableSmmIsBufferOutsideSmmValid ((UINTN)CommBuffer, TempCommBufferSize)) {\r
     DEBUG ((EFI_D_ERROR, "SmmVariableHandler: SMM communication buffer in SMRAM or overflow!\n"));\r
     return EFI_SUCCESS;\r
   }\r
@@ -544,7 +514,7 @@ SmmVariableHandler (
         Status = EFI_ACCESS_DENIED;\r
         goto EXIT;\r
       }\r
-      InfoSize = OFFSET_OF(SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name) \r
+      InfoSize = OFFSET_OF(SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name)\r
                  + SmmVariableHeader->DataSize + SmmVariableHeader->NameSize;\r
 \r
       //\r
@@ -556,6 +526,12 @@ SmmVariableHandler (
         goto EXIT;\r
       }\r
 \r
+      //\r
+      // The VariableSpeculationBarrier() call here is to ensure the previous\r
+      // range/content checks for the CommBuffer have been completed before the\r
+      // subsequent consumption of the CommBuffer content.\r
+      //\r
+      VariableSpeculationBarrier ();\r
       if (SmmVariableHeader->NameSize < sizeof (CHAR16) || SmmVariableHeader->Name[SmmVariableHeader->NameSize/sizeof (CHAR16) - 1] != L'\0') {\r
         //\r
         // Make sure VariableName is A Null-terminated string.\r
@@ -573,7 +549,7 @@ SmmVariableHandler (
                  );\r
       CopyMem (SmmVariableFunctionHeader->Data, mVariableBufferPayload, CommBufferPayloadSize);\r
       break;\r
-      \r
+\r
     case SMM_VARIABLE_FUNCTION_GET_NEXT_VARIABLE_NAME:\r
       if (CommBufferPayloadSize < OFFSET_OF(SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME, Name)) {\r
         DEBUG ((EFI_D_ERROR, "GetNextVariableName: SMM communication buffer size invalid!\n"));\r
@@ -618,7 +594,7 @@ SmmVariableHandler (
                  );\r
       CopyMem (SmmVariableFunctionHeader->Data, mVariableBufferPayload, CommBufferPayloadSize);\r
       break;\r
-      \r
+\r
     case SMM_VARIABLE_FUNCTION_SET_VARIABLE:\r
       if (CommBufferPayloadSize < OFFSET_OF(SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name)) {\r
         DEBUG ((EFI_D_ERROR, "SetVariable: SMM communication buffer size invalid!\n"));\r
@@ -650,6 +626,12 @@ SmmVariableHandler (
         goto EXIT;\r
       }\r
 \r
+      //\r
+      // The VariableSpeculationBarrier() call here is to ensure the previous\r
+      // range/content checks for the CommBuffer have been completed before the\r
+      // subsequent consumption of the CommBuffer content.\r
+      //\r
+      VariableSpeculationBarrier ();\r
       if (SmmVariableHeader->NameSize < sizeof (CHAR16) || SmmVariableHeader->Name[SmmVariableHeader->NameSize/sizeof (CHAR16) - 1] != L'\0') {\r
         //\r
         // Make sure VariableName is A Null-terminated string.\r
@@ -666,7 +648,7 @@ SmmVariableHandler (
                  (UINT8 *)SmmVariableHeader->Name + SmmVariableHeader->NameSize\r
                  );\r
       break;\r
-      \r
+\r
     case SMM_VARIABLE_FUNCTION_QUERY_VARIABLE_INFO:\r
       if (CommBufferPayloadSize < sizeof (SMM_VARIABLE_COMMUNICATE_QUERY_VARIABLE_INFO)) {\r
         DEBUG ((EFI_D_ERROR, "QueryVariableInfo: SMM communication buffer size invalid!\n"));\r
@@ -682,16 +664,34 @@ SmmVariableHandler (
                  );\r
       break;\r
 \r
+    case SMM_VARIABLE_FUNCTION_GET_PAYLOAD_SIZE:\r
+      if (CommBufferPayloadSize < sizeof (SMM_VARIABLE_COMMUNICATE_GET_PAYLOAD_SIZE)) {\r
+        DEBUG ((EFI_D_ERROR, "GetPayloadSize: SMM communication buffer size invalid!\n"));\r
+        return EFI_SUCCESS;\r
+      }\r
+      GetPayloadSize = (SMM_VARIABLE_COMMUNICATE_GET_PAYLOAD_SIZE *) SmmVariableFunctionHeader->Data;\r
+      GetPayloadSize->VariablePayloadSize = mVariableBufferPayloadSize;\r
+      Status = EFI_SUCCESS;\r
+      break;\r
+\r
     case SMM_VARIABLE_FUNCTION_READY_TO_BOOT:\r
-      mEndOfDxe = TRUE;\r
       if (AtRuntime()) {\r
         Status = EFI_UNSUPPORTED;\r
         break;\r
       }\r
+      if (!mEndOfDxe) {\r
+        MorLockInitAtEndOfDxe ();\r
+        mEndOfDxe = TRUE;\r
+        VarCheckLibInitializeAtEndOfDxe (NULL);\r
+        //\r
+        // The initialization for variable quota.\r
+        //\r
+        InitializeVariableQuota ();\r
+      }\r
       ReclaimForOS ();\r
       Status = EFI_SUCCESS;\r
       break;\r
-  \r
+\r
     case SMM_VARIABLE_FUNCTION_EXIT_BOOT_SERVICE:\r
       mAtRuntime = TRUE;\r
       Status = EFI_SUCCESS;\r
@@ -699,66 +699,94 @@ SmmVariableHandler (
 \r
     case SMM_VARIABLE_FUNCTION_GET_STATISTICS:\r
       VariableInfo = (VARIABLE_INFO_ENTRY *) SmmVariableFunctionHeader->Data;\r
-      InfoSize = *CommBufferSize - SMM_VARIABLE_COMMUNICATE_HEADER_SIZE;\r
+      InfoSize = TempCommBufferSize - SMM_VARIABLE_COMMUNICATE_HEADER_SIZE;\r
 \r
       //\r
-      // Do not need to check SmmVariableFunctionHeader->Data in SMRAM here. \r
-      // It is covered by previous CommBuffer check \r
+      // Do not need to check SmmVariableFunctionHeader->Data in SMRAM here.\r
+      // It is covered by previous CommBuffer check\r
+      //\r
+\r
+      //\r
+      // Do not need to check CommBufferSize buffer as it should point to SMRAM\r
+      // that was used by SMM core to cache CommSize from SmmCommunication protocol.\r
       //\r
-     \r
-      if (InternalIsAddressInSmram ((EFI_PHYSICAL_ADDRESS)(UINTN)CommBufferSize, sizeof(UINTN))) {\r
-        DEBUG ((EFI_D_ERROR, "GetStatistics: SMM communication buffer in SMRAM!\n"));\r
-        Status = EFI_ACCESS_DENIED;\r
-        goto EXIT;\r
-      }  \r
 \r
       Status = SmmVariableGetStatistics (VariableInfo, &InfoSize);\r
       *CommBufferSize = InfoSize + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE;\r
       break;\r
 \r
     case SMM_VARIABLE_FUNCTION_LOCK_VARIABLE:\r
-      if (CommBufferPayloadSize < OFFSET_OF(SMM_VARIABLE_COMMUNICATE_LOCK_VARIABLE, Name)) {\r
-        DEBUG ((EFI_D_ERROR, "RequestToLock: SMM communication buffer size invalid!\n"));\r
+      if (mEndOfDxe) {\r
+        Status = EFI_ACCESS_DENIED;\r
+      } else {\r
+        VariableToLock = (SMM_VARIABLE_COMMUNICATE_LOCK_VARIABLE *) SmmVariableFunctionHeader->Data;\r
+        Status = VariableLockRequestToLock (\r
+                   NULL,\r
+                   VariableToLock->Name,\r
+                   &VariableToLock->Guid\r
+                   );\r
+      }\r
+      break;\r
+    case SMM_VARIABLE_FUNCTION_VAR_CHECK_VARIABLE_PROPERTY_SET:\r
+      if (mEndOfDxe) {\r
+        Status = EFI_ACCESS_DENIED;\r
+      } else {\r
+        CommVariableProperty = (SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY *) SmmVariableFunctionHeader->Data;\r
+        Status = VarCheckVariablePropertySet (\r
+                   CommVariableProperty->Name,\r
+                   &CommVariableProperty->Guid,\r
+                   &CommVariableProperty->VariableProperty\r
+                   );\r
+      }\r
+      break;\r
+    case SMM_VARIABLE_FUNCTION_VAR_CHECK_VARIABLE_PROPERTY_GET:\r
+      if (CommBufferPayloadSize < OFFSET_OF (SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY, Name)) {\r
+        DEBUG ((EFI_D_ERROR, "VarCheckVariablePropertyGet: SMM communication buffer size invalid!\n"));\r
         return EFI_SUCCESS;\r
       }\r
       //\r
       // Copy the input communicate buffer payload to pre-allocated SMM variable buffer payload.\r
       //\r
       CopyMem (mVariableBufferPayload, SmmVariableFunctionHeader->Data, CommBufferPayloadSize);\r
-      VariableToLock = (SMM_VARIABLE_COMMUNICATE_LOCK_VARIABLE *) mVariableBufferPayload;\r
-\r
-      if (VariableToLock->NameSize > MAX_ADDRESS - OFFSET_OF (SMM_VARIABLE_COMMUNICATE_LOCK_VARIABLE, Name)) {\r
+      CommVariableProperty = (SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY *) mVariableBufferPayload;\r
+      if ((UINTN) (~0) - CommVariableProperty->NameSize < OFFSET_OF (SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY, Name)) {\r
         //\r
         // Prevent InfoSize overflow happen\r
         //\r
         Status = EFI_ACCESS_DENIED;\r
         goto EXIT;\r
       }\r
+      InfoSize = OFFSET_OF (SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY, Name) + CommVariableProperty->NameSize;\r
 \r
-      if (VariableToLock->NameSize < sizeof (CHAR16) || VariableToLock->Name[VariableToLock->NameSize/sizeof (CHAR16) - 1] != L'\0') {\r
-        //\r
-        // Make sure VariableName is A Null-terminated string.\r
-        //\r
+      //\r
+      // SMRAM range check already covered before\r
+      //\r
+      if (InfoSize > CommBufferPayloadSize) {\r
+        DEBUG ((EFI_D_ERROR, "VarCheckVariablePropertyGet: Data size exceed communication buffer size limit!\n"));\r
         Status = EFI_ACCESS_DENIED;\r
         goto EXIT;\r
       }\r
-      \r
-      InfoSize = OFFSET_OF (SMM_VARIABLE_COMMUNICATE_LOCK_VARIABLE, Name) + VariableToLock->NameSize;\r
-      \r
+\r
       //\r
-      // SMRAM range check already covered before\r
+      // The VariableSpeculationBarrier() call here is to ensure the previous\r
+      // range/content checks for the CommBuffer have been completed before the\r
+      // subsequent consumption of the CommBuffer content.\r
       //\r
-      if (InfoSize > CommBufferPayloadSize) {\r
-        DEBUG ((EFI_D_ERROR, "Data size exceed communication buffer size limit!\n"));\r
+      VariableSpeculationBarrier ();\r
+      if (CommVariableProperty->NameSize < sizeof (CHAR16) || CommVariableProperty->Name[CommVariableProperty->NameSize/sizeof (CHAR16) - 1] != L'\0') {\r
+        //\r
+        // Make sure VariableName is A Null-terminated string.\r
+        //\r
         Status = EFI_ACCESS_DENIED;\r
         goto EXIT;\r
       }\r
 \r
-      Status = VariableLockRequestToLock (\r
-                 NULL,\r
-                 VariableToLock->Name,\r
-                 &VariableToLock->Guid\r
+      Status = VarCheckVariablePropertyGet (\r
+                 CommVariableProperty->Name,\r
+                 &CommVariableProperty->Guid,\r
+                 &CommVariableProperty->VariableProperty\r
                  );\r
+      CopyMem (SmmVariableFunctionHeader->Data, mVariableBufferPayload, CommBufferPayloadSize);\r
       break;\r
 \r
     default:\r
@@ -790,24 +818,56 @@ SmmEndOfDxeCallback (
   IN EFI_HANDLE                           Handle\r
   )\r
 {\r
-  DEBUG ((EFI_D_INFO, "[Variable]END_OF_DXE is signaled\n"));\r
+  DEBUG ((EFI_D_INFO, "[Variable]SMM_END_OF_DXE is signaled\n"));\r
+  MorLockInitAtEndOfDxe ();\r
   mEndOfDxe = TRUE;\r
+  VarCheckLibInitializeAtEndOfDxe (NULL);\r
+  //\r
+  // The initialization for variable quota.\r
+  //\r
+  InitializeVariableQuota ();\r
+  if (PcdGetBool (PcdReclaimVariableSpaceAtEndOfDxe)) {\r
+    ReclaimForOS ();\r
+  }\r
+\r
   return EFI_SUCCESS;\r
 }\r
 \r
+/**\r
+  Initializes variable write service for SMM.\r
+\r
+**/\r
+VOID\r
+VariableWriteServiceInitializeSmm (\r
+  VOID\r
+  )\r
+{\r
+  EFI_STATUS    Status;\r
+\r
+  Status = VariableWriteServiceInitialize ();\r
+  if (EFI_ERROR (Status)) {\r
+    DEBUG ((DEBUG_ERROR, "Variable write service initialization failed. Status = %r\n", Status));\r
+  }\r
+\r
+  //\r
+  // Notify the variable wrapper driver the variable write service is ready\r
+  //\r
+  VariableNotifySmmWriteReady ();\r
+}\r
+\r
 /**\r
   SMM Fault Tolerant Write protocol notification event handler.\r
 \r
-  Non-Volatile variable write may needs FTW protocol to reclaim when \r
+  Non-Volatile variable write may needs FTW protocol to reclaim when\r
   writting variable.\r
-  \r
+\r
   @param  Protocol   Points to the protocol's unique identifier\r
   @param  Interface  Points to the interface instance\r
   @param  Handle     The handle on which the interface was installed\r
 \r
   @retval EFI_SUCCESS   SmmEventCallback runs successfully\r
   @retval EFI_NOT_FOUND The Fvb protocol for variable is not found.\r
-  \r
+\r
  **/\r
 EFI_STATUS\r
 EFIAPI\r
@@ -818,10 +878,12 @@ SmmFtwNotificationEvent (
   )\r
 {\r
   EFI_STATUS                              Status;\r
+  EFI_PHYSICAL_ADDRESS                    VariableStoreBase;\r
   EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL  *FvbProtocol;\r
   EFI_SMM_FAULT_TOLERANT_WRITE_PROTOCOL   *FtwProtocol;\r
   EFI_PHYSICAL_ADDRESS                    NvStorageVariableBase;\r
-  \r
+  UINTN                                   FtwMaxBlockSize;\r
+\r
   if (mVariableModuleGlobal->FvbInstance != NULL) {\r
     return EFI_SUCCESS;\r
   }\r
@@ -834,62 +896,56 @@ SmmFtwNotificationEvent (
     return Status;\r
   }\r
 \r
+  Status = FtwProtocol->GetMaxBlockSize (FtwProtocol, &FtwMaxBlockSize);\r
+  if (!EFI_ERROR (Status)) {\r
+    ASSERT (PcdGet32 (PcdFlashNvStorageVariableSize) <= FtwMaxBlockSize);\r
+  }\r
+\r
+  NvStorageVariableBase = NV_STORAGE_VARIABLE_BASE;\r
+  VariableStoreBase = NvStorageVariableBase + mNvFvHeaderCache->HeaderLength;\r
+\r
+  //\r
+  // Let NonVolatileVariableBase point to flash variable store base directly after FTW ready.\r
+  //\r
+  mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;\r
+\r
   //\r
   // Find the proper FVB protocol for variable.\r
   //\r
-  NvStorageVariableBase = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageVariableBase64);\r
-  if (NvStorageVariableBase == 0) {\r
-    NvStorageVariableBase = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageVariableBase);\r
-  }\r
   Status = GetFvbInfoByAddress (NvStorageVariableBase, NULL, &FvbProtocol);\r
   if (EFI_ERROR (Status)) {\r
     return EFI_NOT_FOUND;\r
   }\r
 \r
   mVariableModuleGlobal->FvbInstance = FvbProtocol;\r
-  \r
-  Status = VariableWriteServiceInitialize ();\r
-  ASSERT_EFI_ERROR (Status);\r
\r
+\r
   //\r
-  // Notify the variable wrapper driver the variable write service is ready\r
+  // Initializes variable write service after FTW was ready.\r
   //\r
-  Status = gBS->InstallProtocolInterface (\r
-                  &mSmmVariableHandle,\r
-                  &gSmmVariableWriteGuid,\r
-                  EFI_NATIVE_INTERFACE,\r
-                  NULL\r
-                  );\r
-  ASSERT_EFI_ERROR (Status);\r
-  \r
+  VariableWriteServiceInitializeSmm ();\r
+\r
   return EFI_SUCCESS;\r
 }\r
 \r
 \r
 /**\r
   Variable Driver main entry point. The Variable driver places the 4 EFI\r
-  runtime services in the EFI System Table and installs arch protocols \r
+  runtime services in the EFI System Table and installs arch protocols\r
   for variable read and write services being available. It also registers\r
   a notification function for an EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE event.\r
 \r
-  @param[in] ImageHandle    The firmware allocated handle for the EFI image.  \r
-  @param[in] SystemTable    A pointer to the EFI System Table.\r
-  \r
   @retval EFI_SUCCESS       Variable service successfully initialized.\r
 \r
 **/\r
 EFI_STATUS\r
 EFIAPI\r
-VariableServiceInitialize (\r
-  IN EFI_HANDLE                           ImageHandle,\r
-  IN EFI_SYSTEM_TABLE                     *SystemTable\r
+MmVariableServiceInitialize (\r
+  VOID\r
   )\r
 {\r
   EFI_STATUS                              Status;\r
   EFI_HANDLE                              VariableHandle;\r
   VOID                                    *SmmFtwRegistration;\r
-  EFI_SMM_ACCESS2_PROTOCOL                *SmmAccess;\r
-  UINTN                                   Size;\r
   VOID                                    *SmmEndOfDxeRegistration;\r
 \r
   //\r
@@ -902,7 +958,7 @@ VariableServiceInitialize (
   // Install the Smm Variable Protocol on a new handle.\r
   //\r
   VariableHandle = NULL;\r
-  Status = gSmst->SmmInstallProtocolInterface (\r
+  Status = gMmst->MmInstallProtocolInterface (\r
                     &VariableHandle,\r
                     &gEfiSmmVariableProtocolGuid,\r
                     EFI_NATIVE_INTERFACE,\r
@@ -910,32 +966,18 @@ VariableServiceInitialize (
                     );\r
   ASSERT_EFI_ERROR (Status);\r
 \r
-  //\r
-  // Get SMRAM information\r
-  //\r
-  Status = gBS->LocateProtocol (&gEfiSmmAccess2ProtocolGuid, NULL, (VOID **)&SmmAccess);\r
-  ASSERT_EFI_ERROR (Status);\r
-\r
-  Size = 0;\r
-  Status = SmmAccess->GetCapabilities (SmmAccess, &Size, NULL);\r
-  ASSERT (Status == EFI_BUFFER_TOO_SMALL);\r
-\r
-  Status = gSmst->SmmAllocatePool (\r
-                    EfiRuntimeServicesData,\r
-                    Size,\r
-                    (VOID **)&mSmramRanges\r
+  Status = gMmst->MmInstallProtocolInterface (\r
+                    &VariableHandle,\r
+                    &gEdkiiSmmVarCheckProtocolGuid,\r
+                    EFI_NATIVE_INTERFACE,\r
+                    &mSmmVarCheck\r
                     );\r
   ASSERT_EFI_ERROR (Status);\r
 \r
-  Status = SmmAccess->GetCapabilities (SmmAccess, &Size, mSmramRanges);\r
-  ASSERT_EFI_ERROR (Status);\r
-\r
-  mSmramRangeCount = Size / sizeof (EFI_SMRAM_DESCRIPTOR);\r
-\r
-  mVariableBufferPayloadSize = MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxHardwareErrorVariableSize)) +\r
-                               OFFSET_OF (SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name) - sizeof (VARIABLE_HEADER);\r
+  mVariableBufferPayloadSize = GetMaxVariableSize () +\r
+                               OFFSET_OF (SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY, Name) - GetVariableHeaderSize ();\r
 \r
-  Status = gSmst->SmmAllocatePool (\r
+  Status = gMmst->MmAllocatePool (\r
                     EfiRuntimeServicesData,\r
                     mVariableBufferPayloadSize,\r
                     (VOID **)&mVariableBufferPayload\r
@@ -946,42 +988,43 @@ VariableServiceInitialize (
   /// Register SMM variable SMI handler\r
   ///\r
   VariableHandle = NULL;\r
-  Status = gSmst->SmiHandlerRegister (SmmVariableHandler, &gEfiSmmVariableProtocolGuid, &VariableHandle);\r
+  Status = gMmst->MmiHandlerRegister (SmmVariableHandler, &gEfiSmmVariableProtocolGuid, &VariableHandle);\r
   ASSERT_EFI_ERROR (Status);\r
-  \r
+\r
   //\r
   // Notify the variable wrapper driver the variable service is ready\r
   //\r
-  Status = SystemTable->BootServices->InstallProtocolInterface (\r
-                                        &mVariableHandle,\r
-                                        &gEfiSmmVariableProtocolGuid,\r
-                                        EFI_NATIVE_INTERFACE,\r
-                                        &gSmmVariable\r
-                                        );\r
-  ASSERT_EFI_ERROR (Status);\r
\r
+  VariableNotifySmmReady ();\r
+\r
   //\r
   // Register EFI_SMM_END_OF_DXE_PROTOCOL_GUID notify function.\r
   //\r
-  Status = gSmst->SmmRegisterProtocolNotify (\r
-                    &gEfiSmmEndOfDxeProtocolGuid,\r
+  Status = gMmst->MmRegisterProtocolNotify (\r
+                    &gEfiMmEndOfDxeProtocolGuid,\r
                     SmmEndOfDxeCallback,\r
                     &SmmEndOfDxeRegistration\r
                     );\r
   ASSERT_EFI_ERROR (Status);\r
 \r
-  //\r
-  // Register FtwNotificationEvent () notify function.\r
-  // \r
-  Status = gSmst->SmmRegisterProtocolNotify (\r
-                    &gEfiSmmFaultTolerantWriteProtocolGuid,\r
-                    SmmFtwNotificationEvent,\r
-                    &SmmFtwRegistration\r
-                    );\r
-  ASSERT_EFI_ERROR (Status);\r
+  if (!PcdGetBool (PcdEmuVariableNvModeEnable)) {\r
+    //\r
+    // Register FtwNotificationEvent () notify function.\r
+    //\r
+    Status = gMmst->MmRegisterProtocolNotify (\r
+                      &gEfiSmmFaultTolerantWriteProtocolGuid,\r
+                      SmmFtwNotificationEvent,\r
+                      &SmmFtwRegistration\r
+                      );\r
+    ASSERT_EFI_ERROR (Status);\r
+\r
+    SmmFtwNotificationEvent (NULL, NULL, NULL);\r
+  } else {\r
+    //\r
+    // Emulated non-volatile variable mode does not depend on FVB and FTW.\r
+    //\r
+    VariableWriteServiceInitializeSmm ();\r
+  }\r
 \r
-  SmmFtwNotificationEvent (NULL, NULL, NULL);\r
-  \r
   return EFI_SUCCESS;\r
 }\r
 \r