public inbox for devel@edk2.groups.io
 help / color / mirror / Atom feed
* [PATCH V7 00/10] UEFI Variable SMI Reduction
@ 2019-11-01 17:34 Kubacki, Michael A
  2019-11-01 17:34 ` [PATCH V7 01/10] MdeModulePkg/Variable: Consolidate common parsing functions Kubacki, Michael A
                   ` (10 more replies)
  0 siblings, 11 replies; 14+ messages in thread
From: Kubacki, Michael A @ 2019-11-01 17:34 UTC (permalink / raw)
  To: devel
  Cc: Dandan Bi, Ard Biesheuvel, Eric Dong, Laszlo Ersek, Liming Gao,
	Michael D Kinney, Ray Ni, Jian J Wang, Hao A Wu, Jiewen Yao

REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2220

V7 Changes:
 [PATCH V6 07/10] MdeModulePkg/Variable: Add RT GetVariable() cache support
 * Remove VariableRuntimeCache.c and VariableRuntimeCache.h from
   VariableSmmRuntimeDxe.inf since they are not needed to build the module.

V6 Changes:
 [PATCH V5 07/10] MdeModulePkg/Variable: Add RT GetVariable() cache support
 The most significant change is:
 * Free mVariableRuntimeHobCacheBuffer in CheckForRuntimeCacheSync () in
   VariableSmmRuntimeDxe.c with FreePages () instead of FreePool ().
 This issue was not found in earlier testing because on the initial set of
 platforms tested, the variable HOB flush was finished prior to the variable
 HOB runtime cache buffer being allocated so the FreePages () call was not
 executed.

 The remaining changes did not affect testing but are included for robustness:
 * Pass EFI_OPTIONAL_PTR for the DebugDisposition type in the EfiConvertPointer ()
   calls for mVariableRuntimeHobCacheBuffer, mVariableRuntimeNvCacheBuffer, and
   mVariableRuntimeVolatileCacheBuffer in VariableAddressChangeEvent () in
   VariableSmmRuntimeDxe.c as these buffers will not be allocated if the runtime
   cache is disabled.
 * In the SMM_VARIABLE_FUNCTION_INIT_RUNTIME_VARIABLE_CACHE_CONTEXT case in
   SmmVariableHandler () in VariableSmm.c, explicitly verify that
   VariableRuntimeHobCache.Store is not NULL in addition to checking that
   VariableGlobal.HobVariableBase is not set to zero (variable HOB is flushed)
   before writing to VariableRuntimeHobCache.Store.

V5 Changes:
 [PATCH V4 07/10] MdeModulePkg/Variable: Add RT GetVariable() cache support
 * Increased validation of the runtime buffers passed in the SMM comm buffer
   SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT structure to the
   SMM_VARIABLE_FUNCTION_INIT_RUNTIME_VARIABLE_CACHE_CONTEXT function in
   SmmVariableHandler () in VariableSmm.c.
 * Most notably, each runtime buffer given is checked to ensure its memory
   range does not overlap with SMRAM ranges via VariableSmmIsBufferOutsideSmmValid ().

V4 Changes:
 [PATCH V3 7/9] MdeModulePkg/Variable: Add RT GetVariable() cache support
 * Set gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache to FALSE
   by default in MdeModulePkg.dec.

 * Added a new patch to set gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache
   to TRUE at the end of the patch series. This allows someone to bisect an issue at
   patch #7 or patch #8 in the series with no change in variable caching behavior. The
   runtime cache variable logic would be applied explicitly in V4 patch #10.

V3 Changes:
 [PATCH V2 1/9] MdeModulePkg/Variable: Consolidate common parsing functions
 * Removed GUIDs added to VariableStandaloneMm.inf that are not required.
 * Added more details to the commit message describing the criteria of
   moving the chosen functions to VariableParsing.c.

 [PATCH V2 2/9] MdeModulePkg/Variable: Parameterize GetNextVariableEx() store list
 * RenamedGetNextVariableEx () to VariableServiceGetNextVariableInternal ()
 * Updated comments in VariableServiceGetNextVariableInternal () to refer to
   "FindVariablEx ()" instead of "FindVariable ()" since FindVariableEx ()
   is not used in the function.

 [PATCH V2 3/9] MdeModulePkg/Variable: Parameterize VARIABLE_INFO_ENTRY buffer
 * Updated the commit message to clarify the message "structure can be updated
   outside the fixed global variable".

 [edk2-devel] [PATCH V2 4/9] MdeModulePkg/Variable: Add local auth status in VariableParsing
 * Remove the function InitVariableParsing ()
 * Remove the mAuthFormat global variable and instead add a BOOLEAN parameter
   to all functions that require variable authentication information  to
   indicate if authenticated variables are used.
   * This allows the authenticated variable status to be tracked in one place in
     each variable driver in the SMM variable solution (VariableSmmRuntimeDxe
     and VariableSmm).

 [edk2-devel] [PATCH V2 5/9] MdeModulePkg/Variable: Add a file for NV variable functions
 * Added the following non-volatile related functions to VariableNonVolatile.c
   from Variable.c:
   * InitRealNonVolatileVariableStore ()
   * InitEmuNonVolatileVariableStore ()
   * InitNonVolatileVariableStore ()

 [edk2-devel] [PATCH V2 7/9] MdeModulePkg/Variable: Add RT GetVariable() cache support
 * Added a FeaturePCD to control enabling the runtime variable cache -
   gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache.
 * Removed usage of the TimerLib and the wait to acquire
   mVariableRuntimeCacheReadLock. Can rely on the UEFI specification
   restrictions on Runtime Services callers.
 * Removed the EFIAPI keyword from internal functions.
 * Removed PCDs in VariableSmmRuntimeDxe.inf not required.
 * Removed the HobVariableBackupBase variable no longer required.
 * Renamed SynchronizeRuntimeVariableCacheEx () to better reflect usage.
 * Renamed functions in VariableRuntimeCache.c to better reflect usage.
 * Introduced a local variable in FlushPendingRuntimeVariableCacheUpdates ()
   to reduce duplication of 
   mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.
 * Corrected the macro used in SmmVariableHandler () to
   SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT.
 * Remove usage of the EDKII_PI_SMM_COMMUNICATION_REGION_TABLE to acquire a
   CommBuffer from the EFI System Table and use the same runtime CommBuffer
   allocated for variable SMM communicate calls.

 [PATCH V2 8/9] MdeModulePkg/Variable: Add RT GetNextVariableName() cache support
 * Removed usage of the TimerLib and the wait to acquire
   mVariableRuntimeCacheReadLock. Can rely on the UEFI specification restrictions
   on Runtime Services callers.

 * Added a new patch to disable gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache
   for all OvmfPkg package builds as requested by maintainer Laszlo Ersek.

V2 Changes:

Patch #1 in V1 both moved functions to VariableParsing.c and modified some
functionality in those functions. In V2, the functions are first moved and
then functionality is modified in subsequent patches. This resulted in the
following new patches in the V2 patch series:

 1. MdeModulePkg/Variable: Parameterize GetNextVariableEx() store list
 2. MdeModulePkg/Variable: Parameterize VARIABLE_INFO_ENTRY buffer
 3. MdeModulePkg/Variable: Add local auth status in VariableParsing
 4. MdeModulePkg/Variable: Add a file for NV variable functions

Apart from this refactor in the patches, no functionally impacting changes
were made.

Overview
---------
This patch series reduces SMM usage when using VariableSmmRuntimeDxe with
VariableSmm. It does so by eliminating SMM usage for runtime service
GetVariable () and GetNextVariableName () invocations. Most UEFI variable
usage in typical systems after the variable store is initialized
(e.g. manufacturing boots) is due to GetVariable ( ) and
GetNextVariableName () not SetVariable (). GetVariable () calls can regularly
exceed 100 per boot while SetVariable () calls typically remain less than 10
per boot. By focusing on the common case, the majority of overhead associated
with SMM can be avoided while still using existing and proven code for
operations such as variable authentication that require an isolated execution
environment.

 * Advantage: Reduces overall system SMM usage
 * Disadvantage: Requires more Runtime data memory usage

The runtime cache behavior described for this patch series is enabled by
default but can be disabled with a new FeaturePCD added to MdeModulePkg.dec:
  gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache

The reaminder of this blurb describes the changes and behavior when the PCD
is set to TRUE.

Initial Performance Observations
---------------------------------
 * With these proposed changes, an Intel Atom based SoC saw GetVariable ( )
   time for an existing variable reduce from ~220us to ~5us.

Major Changes
--------------
 1. Two UEFI variable caches will be maintained.
     a. "Runtime Cache" - Maintained in VariableSmmRuntimeDxe. Used to serve
         runtime service GetVariable () and GetNextVariableName () callers.
     b. "SMM cache" - Maintained in VariableSmm to service SMM GetVariable ()
         and GetNextVariableName () callers.
         i. A cache in SMRAM is retained so SMM modules do not operate on data
            outside SMRAM.
 2. A new UEFI variable read and write flow will be used as described below.

At any given time, the two caches would be coherent. On a variable write, the
runtime cache is only updated after validation in SMM and, in the case of a
non-volatile UEFI variable, the variable must also be successfully written to
non-volatile storage.

Prior RFC Feedback Addressed
-----------------------------
RFC sent Sept. 5, 2019: https://edk2.groups.io/g/devel/message/46939

1. UEFI variable data retrieval from a ring 0 buffer

   A common concern with this proposed set of changes is the potential security
   threat presented by serving runtime services callers from a ring 0 memory
   buffer of EfiRuntimeServicesData type. The conclusion was that this change
   does not fundamentally alter the attack surface. The UEFI variable Runtime
   Services are invoked from ring 0 and the data already travels through ring
   0 buffers (such as the SMM communicate buffer) to reach the caller. Even
   today if ring 0 is assumed to be malicious, the malicious code may keep one
   AP in a loop to monitor the communication data, when the BSP gets an
   (authenticated) variable. When the communication buffer is updated and the
   status is set to EFI_SUCCESS, the AP may modify the communication buffer
   contents such the tampered data is returned to the BSP caller. Or an
   interrupt handler on the BSP may alter the communication buffer contents
   before the data is returned to the caller. In summary, this was not found to
   introduce any attack not possible today.

2. VarCheckLib impact

   VarCheckLib plays a role in SetVariable () calls. This patch series only
   changes GetVariable () behavior. Therefore, VarCheckLib is expected to
   have no impact due to these changes.

Testing Performed
------------------
This code was tested with the master branch of edk2 on an Intel Kaby Lake U
and Intel Whiskey Lake U reference validation platform. The set of tests
performed included:

1.  Boot from S5 to Windows 10 OS with SMM variables enabled and
    the variable runtime cache enabled.
2.  Boot from S5 to Ubuntu 18.04.1 LTS with SMM variable enabled
    and the variable runtime cache enabled.
3.  Boot from S5 to Windows 10 OS with SMM variables enabled and
    the variable runtime cache disabled.
4.  Boot from S5 to Ubuntu 18.04.1 LTS with SMM variable enabled
    and the variable runtime cache disabled.
5.  Boot from S5 to EFI shell with DXE variables enabled.
    (commit 2de1f611be broke OvmfPkgIa32X64 boot regardless of
     this patch series; testing without this commit was successful)
6.  Dump UEFI variable store at shell with dmpstore to verify contents.
7.  Dump NvStorage FV from SPI flash after boot to verify contents written.
8.  Dump UEFI variable statistics with VariableInfo at shell.
9.  Boot with emulated variables enabled.
10. Cycles of adding and deleting a UEFI variable to verify cache correctness.
11. Set OsIndications to stop at FW UI to verify cache load of non-volatile
    contents.

Why Keep SMM on Variable Writes
--------------------------------
 * SMM provides a ubiquitous isolated execution environment in x86 for
   authenticated UEFI variables.
 * BIOS region SPI flash write restrictions to SMM in platforms today can
   be retained.

Today's UEFI Variable Cache (for reference)
--------------------------------------------
 * Maintained in SMRAM via VariableSmm.
 * A "write-through" cache of variable data in the form of a UEFI variable
   store.
 * Non-volatile and volatile variables are maintained in separate buffers
  (variable stores).

Runtime & SMM Cache Coherency
------------------------------
The non-volatile cache should always accurately reflect non-volatile storage
contents (done today) and the "SMM cache" and "Runtime cache" should always be
coherent on access. The runtime cache is updated by VariableSmm.

Updating both caches from within a SMM SetVariable () operation is fairly
straightforward but a race condition can occur if an SMI occurs during the
execution of runtime code reading from the runtime cache. To handle this case,
a runtime cache read lock is introduced that explicitly moves pending updates
from SMM to the runtime cache if an SMM update occurs while the runtime cache
is locked. Note that it is not expected a Runtime services call will interrupt
SMM processing since all CPU cores rendezvous in SMM.

New Key Elements for Coherence
-------------------------------
Runtime DXE (VariableSmmRuntimeDxe)
 1. RuntimeCacheReadLock - A global lock used to lock read access to the
                           runtime cache.
 2. RuntimeCachePendingUpdate - A global flag used to notify runtime code of a
                                pending cache update in SMM.

SMM (VariableSmm)
 1. FlushRuntimeCachePendingUpdate SMI - A SW SMI handler that synchronizes
                                         the runtime cache buffer with the SMM
                                         cache buffer.

Proposed Runtime DXE Read Flow
-------------------------------
 1. Acquire RuntimeCacheReadLock
 2. If RuntimeCachePendingUpdate flag (rare) is set then:
     2.a. Trigger FlushRuntimeCachePendingUpdate SMI
     2.b. Verify RuntimeCachePendingUpdate flag is cleared
 3. Perform read from RuntimeCache
 4. Release RuntimeCacheReadLock

Proposed FlushRuntimeCachePendingUpdate SMI
--------------------------------------------
 1. If RuntimeCachePendingUpdate flag is not set:
     1.a. Return
 2. Copy the data at RuntimeCachePendingOffset of RuntimeCachePendingLength to
    RuntimeCache
 3. Clear the RuntimeCachePendingUpdate flag

Proposed SMM Write Flow
------------------------
 1. Perform variable authentication and non-volatile write. If either fail,
    return an error to the caller.
 2. If RuntimeCacheReadLock is set then:
     2.a. Set RuntimeCachePendingUpdate flag
     2.b. Update RuntimeCachePendingOffset and RuntimeCachePendingLength to
          cover the a superset of the pending chunk (for simplicity, the
          entire variable store is currently synchronized).
3. Else:
     3.a. Update RuntimeCache
4. Update SmmCache
     - Note: RT read cannot occur during SMI processing since all cores are
             locked in SMM.

Cc: Dandan Bi <dandan.bi@intel.com>
Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Eric Dong <eric.dong@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Cc: Liming Gao <liming.gao@intel.com>
Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Hao A Wu <hao.a.wu@intel.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Signed-off-by: Michael Kubacki <michael.a.kubacki@intel.com>

Michael Kubacki (10):
  MdeModulePkg/Variable: Consolidate common parsing functions
  MdeModulePkg/Variable: Parameterize GetNextVariableInternal () stores
  MdeModulePkg/Variable: Parameterize VARIABLE_INFO_ENTRY buffer
  MdeModulePkg/Variable: Parameterize auth status in VariableParsing
  MdeModulePkg/Variable: Add a file for NV variable functions
  MdeModulePkg VariableInfo: Always consider RT DXE and SMM stats
  MdeModulePkg/Variable: Add RT GetVariable() cache support
  MdeModulePkg/Variable: Add RT GetNextVariableName() cache support
  OvmfPkg: Disable variable runtime cache
  MdeModulePkg: Enable variable runtime cache by default

 MdeModulePkg/MdeModulePkg.dec                                        |   12 +
 OvmfPkg/OvmfPkgIa32.dsc                                              |    1 +
 OvmfPkg/OvmfPkgIa32X64.dsc                                           |    1 +
 OvmfPkg/OvmfPkgX64.dsc                                               |    1 +
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf    |    6 +
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf           |    6 +
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf |   18 +-
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf  |    6 +
 MdeModulePkg/Include/Guid/SmmVariableCommon.h                        |   29 +-
 MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h                |  151 +--
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.h     |   67 +
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h         |  347 +++++
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.h    |   51 +
 MdeModulePkg/Application/VariableInfo/VariableInfo.c                 |   37 +-
 MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c                | 1373 ++++----------------
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c           |   24 +-
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.c     |  334 +++++
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c         |  786 +++++++++++
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.c    |  153 +++
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c             |  195 ++-
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c   |  655 +++++++++-
 21 files changed, 2924 insertions(+), 1329 deletions(-)
 create mode 100644 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.h
 create mode 100644 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h
 create mode 100644 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.h
 create mode 100644 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.c
 create mode 100644 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c
 create mode 100644 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.c

-- 
2.16.2.windows.1


^ permalink raw reply	[flat|nested] 14+ messages in thread

* [PATCH V7 01/10] MdeModulePkg/Variable: Consolidate common parsing functions
  2019-11-01 17:34 [PATCH V7 00/10] UEFI Variable SMI Reduction Kubacki, Michael A
@ 2019-11-01 17:34 ` Kubacki, Michael A
  2019-11-01 17:34 ` [PATCH V7 02/10] MdeModulePkg/Variable: Parameterize GetNextVariableInternal () stores Kubacki, Michael A
                   ` (9 subsequent siblings)
  10 siblings, 0 replies; 14+ messages in thread
From: Kubacki, Michael A @ 2019-11-01 17:34 UTC (permalink / raw)
  To: devel
  Cc: Dandan Bi, Ard Biesheuvel, Eric Dong, Laszlo Ersek, Liming Gao,
	Michael D Kinney, Ray Ni, Jian J Wang, Hao A Wu, Jiewen Yao

This change moves the following functions into a dedicated file
so they may be used in other variable files as needed. These are
commonly needed for basic variable data structure parsing
operations. The functions are grouped together in VariableParsing.c
to support cohesiveness for these operations in the file.
Furthermore, it reduces the overall size of the common Variable.c
file.

 * DataSizeOfVariable ()
 * FindVariableEx ()
 * GetEndPointer ()
 * GetNextVariablePtr ()
 * GetStartPointer ()
 * GetVariableDataOffset ()
 * GetVariableDataPtr ()
 * GetVariableHeaderSize ()
 * GetVariableNamePtr ()
 * GetVariableStoreStatus ()
 * GetVendorGuidPtr ()
 * IsValidVariableHeader ()
 * NameSizeOfVariable ()
 * SetDataSizeOfVariable ()
 * SetNameSizeOfVariable ()
 * UpdateVariableInfo ()
 * VariableCompareTimeStampInternal ()
 * VariableServiceGetNextVariableInternal ()

Cc: Dandan Bi <dandan.bi@intel.com>
Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Eric Dong <eric.dong@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Cc: Liming Gao <liming.gao@intel.com>
Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Hao A Wu <hao.a.wu@intel.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Signed-off-by: Michael Kubacki <michael.a.kubacki@intel.com>
---
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf   |   2 +
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf          |   2 +
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf |   2 +
 MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h               | 119 ----
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h        | 306 ++++++++
 MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c               | 726 +------------------
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c          |   3 +-
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c        | 731 ++++++++++++++++++++
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c            |   1 +
 9 files changed, 1047 insertions(+), 845 deletions(-)

diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
index 641376c9c5..c35e5fe787 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
@@ -36,6 +36,8 @@
   Variable.c
   VariableDxe.c
   Variable.h
+  VariableParsing.c
+  VariableParsing.h
   PrivilegePolymorphic.h
   Measurement.c
   TcgMorLockDxe.c
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf
index 0a160d269d..626738b9c7 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf
@@ -45,6 +45,8 @@
   Variable.c
   VariableTraditionalMm.c
   VariableSmm.c
+  VariableParsing.c
+  VariableParsing.h
   VarCheck.c
   Variable.h
   PrivilegePolymorphic.h
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf
index 21bc81163b..ff714b193a 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf
@@ -45,6 +45,8 @@
   Variable.c
   VariableSmm.c
   VariableStandaloneMm.c
+  VariableParsing.c
+  VariableParsing.h
   VarCheck.c
   Variable.h
   PrivilegePolymorphic.h
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h
index 9eac43759f..fb574b2e32 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h
@@ -179,89 +179,6 @@ FindVariable (
   IN  BOOLEAN                 IgnoreRtCheck
   );
 
-/**
-
-  Gets the pointer to the end of the variable storage area.
-
-  This function gets pointer to the end of the variable storage
-  area, according to the input variable store header.
-
-  @param VarStoreHeader  Pointer to the Variable Store Header.
-
-  @return Pointer to the end of the variable storage area.
-
-**/
-VARIABLE_HEADER *
-GetEndPointer (
-  IN VARIABLE_STORE_HEADER       *VarStoreHeader
-  );
-
-/**
-  This code gets the size of variable header.
-
-  @return Size of variable header in bytes in type UINTN.
-
-**/
-UINTN
-GetVariableHeaderSize (
-  VOID
-  );
-
-/**
-
-  This code gets the pointer to the variable name.
-
-  @param Variable        Pointer to the Variable Header.
-
-  @return Pointer to Variable Name which is Unicode encoding.
-
-**/
-CHAR16 *
-GetVariableNamePtr (
-  IN  VARIABLE_HEADER   *Variable
-  );
-
-/**
-  This code gets the pointer to the variable guid.
-
-  @param Variable   Pointer to the Variable Header.
-
-  @return A EFI_GUID* pointer to Vendor Guid.
-
-**/
-EFI_GUID *
-GetVendorGuidPtr (
-  IN VARIABLE_HEADER    *Variable
-  );
-
-/**
-
-  This code gets the pointer to the variable data.
-
-  @param Variable        Pointer to the Variable Header.
-
-  @return Pointer to Variable Data.
-
-**/
-UINT8 *
-GetVariableDataPtr (
-  IN  VARIABLE_HEADER   *Variable
-  );
-
-/**
-
-  This code gets the size of variable data.
-
-  @param Variable        Pointer to the Variable Header.
-
-  @return Size of variable in bytes.
-
-**/
-UINTN
-DataSizeOfVariable (
-  IN  VARIABLE_HEADER   *Variable
-  );
-
 /**
   This function is to check if the remaining variable space is enough to set
   all Variables from argument list successfully. The purpose of the check
@@ -450,17 +367,6 @@ ReclaimForOS(
   VOID
   );
 
-/**
-  Get non-volatile maximum variable size.
-
-  @return Non-volatile maximum variable size.
-
-**/
-UINTN
-GetNonVolatileMaxVariableSize (
-  VOID
-  );
-
 /**
   Get maximum variable size, covering both non-volatile and volatile variables.
 
@@ -546,31 +452,6 @@ VariableServiceGetVariable (
   OUT     VOID              *Data OPTIONAL
   );
 
-/**
-  This code Finds the Next available variable.
-
-  Caution: This function may receive untrusted input.
-  This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
-
-  @param[in] VariableName   Pointer to variable name.
-  @param[in] VendorGuid     Variable Vendor Guid.
-  @param[out] VariablePtr   Pointer to variable header address.
-
-  @retval EFI_SUCCESS           The function completed successfully.
-  @retval EFI_NOT_FOUND         The next variable was not found.
-  @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while VendorGuid is NULL.
-  @retval EFI_INVALID_PARAMETER The input values of VariableName and VendorGuid are not a name and
-                                GUID of an existing variable.
-
-**/
-EFI_STATUS
-EFIAPI
-VariableServiceGetNextVariableInternal (
-  IN  CHAR16                *VariableName,
-  IN  EFI_GUID              *VendorGuid,
-  OUT VARIABLE_HEADER       **VariablePtr
-  );
-
 /**
 
   This code Finds the Next available variable.
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h
new file mode 100644
index 0000000000..b0d7f76bd8
--- /dev/null
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h
@@ -0,0 +1,306 @@
+/** @file
+  Functions in this module are associated with variable parsing operations and
+  are intended to be usable across variable driver source files.
+
+Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef _VARIABLE_PARSING_H_
+#define _VARIABLE_PARSING_H_
+
+#include <Guid/ImageAuthentication.h>
+#include "Variable.h"
+
+/**
+
+  This code checks if variable header is valid or not.
+
+  @param[in] Variable           Pointer to the Variable Header.
+  @param[in] VariableStoreEnd   Pointer to the Variable Store End.
+
+  @retval TRUE              Variable header is valid.
+  @retval FALSE             Variable header is not valid.
+
+**/
+BOOLEAN
+IsValidVariableHeader (
+  IN  VARIABLE_HEADER       *Variable,
+  IN  VARIABLE_HEADER       *VariableStoreEnd
+  );
+
+/**
+
+  This code gets the current status of Variable Store.
+
+  @param[in] VarStoreHeader  Pointer to the Variable Store Header.
+
+  @retval EfiRaw         Variable store status is raw.
+  @retval EfiValid       Variable store status is valid.
+  @retval EfiInvalid     Variable store status is invalid.
+
+**/
+VARIABLE_STORE_STATUS
+GetVariableStoreStatus (
+  IN VARIABLE_STORE_HEADER *VarStoreHeader
+  );
+
+/**
+  This code gets the size of variable header.
+
+  @return Size of variable header in bytes in type UINTN.
+
+**/
+UINTN
+GetVariableHeaderSize (
+  VOID
+  );
+
+/**
+
+  This code gets the size of name of variable.
+
+  @param Variable        Pointer to the Variable Header.
+
+  @return UINTN          Size of variable in bytes.
+
+**/
+UINTN
+NameSizeOfVariable (
+  IN  VARIABLE_HEADER   *Variable
+  );
+
+/**
+  This code sets the size of name of variable.
+
+  @param[in] Variable   Pointer to the Variable Header.
+  @param[in] NameSize   Name size to set.
+
+**/
+VOID
+SetNameSizeOfVariable (
+  IN VARIABLE_HEADER    *Variable,
+  IN UINTN              NameSize
+  );
+
+/**
+
+  This code gets the size of variable data.
+
+  @param Variable        Pointer to the Variable Header.
+
+  @return Size of variable in bytes.
+
+**/
+UINTN
+DataSizeOfVariable (
+  IN  VARIABLE_HEADER   *Variable
+  );
+
+/**
+  This code sets the size of variable data.
+
+  @param[in] Variable   Pointer to the Variable Header.
+  @param[in] DataSize   Data size to set.
+
+**/
+VOID
+SetDataSizeOfVariable (
+  IN VARIABLE_HEADER    *Variable,
+  IN UINTN              DataSize
+  );
+
+/**
+
+  This code gets the pointer to the variable name.
+
+  @param Variable        Pointer to the Variable Header.
+
+  @return Pointer to Variable Name which is Unicode encoding.
+
+**/
+CHAR16 *
+GetVariableNamePtr (
+  IN  VARIABLE_HEADER   *Variable
+  );
+
+/**
+  This code gets the pointer to the variable guid.
+
+  @param Variable   Pointer to the Variable Header.
+
+  @return A EFI_GUID* pointer to Vendor Guid.
+
+**/
+EFI_GUID *
+GetVendorGuidPtr (
+  IN VARIABLE_HEADER    *Variable
+  );
+
+/**
+
+  This code gets the pointer to the variable data.
+
+  @param Variable        Pointer to the Variable Header.
+
+  @return Pointer to Variable Data.
+
+**/
+UINT8 *
+GetVariableDataPtr (
+  IN  VARIABLE_HEADER   *Variable
+  );
+
+/**
+  This code gets the variable data offset related to variable header.
+
+  @param Variable        Pointer to the Variable Header.
+
+  @return Variable Data offset.
+
+**/
+UINTN
+GetVariableDataOffset (
+  IN  VARIABLE_HEADER   *Variable
+  );
+
+/**
+
+  This code gets the pointer to the next variable header.
+
+  @param Variable        Pointer to the Variable Header.
+
+  @return Pointer to next variable header.
+
+**/
+VARIABLE_HEADER *
+GetNextVariablePtr (
+  IN  VARIABLE_HEADER   *Variable
+  );
+
+/**
+
+  Gets the pointer to the first variable header in given variable store area.
+
+  @param[in] VarStoreHeader  Pointer to the Variable Store Header.
+
+  @return Pointer to the first variable header.
+
+**/
+VARIABLE_HEADER *
+GetStartPointer (
+  IN VARIABLE_STORE_HEADER       *VarStoreHeader
+  );
+
+/**
+
+  Gets the pointer to the end of the variable storage area.
+
+  This function gets pointer to the end of the variable storage
+  area, according to the input variable store header.
+
+  @param[in] VarStoreHeader  Pointer to the Variable Store Header.
+
+  @return Pointer to the end of the variable storage area.
+
+**/
+VARIABLE_HEADER *
+GetEndPointer (
+  IN VARIABLE_STORE_HEADER       *VarStoreHeader
+  );
+
+/**
+  Compare two EFI_TIME data.
+
+
+  @param[in] FirstTime       A pointer to the first EFI_TIME data.
+  @param[in] SecondTime      A pointer to the second EFI_TIME data.
+
+  @retval  TRUE              The FirstTime is not later than the SecondTime.
+  @retval  FALSE             The FirstTime is later than the SecondTime.
+
+**/
+BOOLEAN
+VariableCompareTimeStampInternal (
+  IN EFI_TIME               *FirstTime,
+  IN EFI_TIME               *SecondTime
+  );
+
+/**
+  Find the variable in the specified variable store.
+
+  @param[in]       VariableName        Name of the variable to be found
+  @param[in]       VendorGuid          Vendor GUID to be found.
+  @param[in]       IgnoreRtCheck       Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute
+                                       check at runtime when searching variable.
+  @param[in, out]  PtrTrack            Variable Track Pointer structure that contains Variable Information.
+
+  @retval          EFI_SUCCESS         Variable found successfully
+  @retval          EFI_NOT_FOUND       Variable not found
+**/
+EFI_STATUS
+FindVariableEx (
+  IN     CHAR16                  *VariableName,
+  IN     EFI_GUID                *VendorGuid,
+  IN     BOOLEAN                 IgnoreRtCheck,
+  IN OUT VARIABLE_POINTER_TRACK  *PtrTrack
+  );
+
+/**
+  This code Finds the Next available variable.
+
+  Caution: This function may receive untrusted input.
+  This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
+
+  @param[in]  VariableName  Pointer to variable name.
+  @param[in]  VendorGuid    Variable Vendor Guid.
+  @param[out] VariablePtr   Pointer to variable header address.
+
+  @retval EFI_SUCCESS           The function completed successfully.
+  @retval EFI_NOT_FOUND         The next variable was not found.
+  @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while VendorGuid is NULL.
+  @retval EFI_INVALID_PARAMETER The input values of VariableName and VendorGuid are not a name and
+                                GUID of an existing variable.
+
+**/
+EFI_STATUS
+EFIAPI
+VariableServiceGetNextVariableInternal (
+  IN  CHAR16                *VariableName,
+  IN  EFI_GUID              *VendorGuid,
+  OUT VARIABLE_HEADER       **VariablePtr
+  );
+
+/**
+  Routine used to track statistical information about variable usage.
+  The data is stored in the EFI system table so it can be accessed later.
+  VariableInfo.efi can dump out the table. Only Boot Services variable
+  accesses are tracked by this code. The PcdVariableCollectStatistics
+  build flag controls if this feature is enabled.
+
+  A read that hits in the cache will have Read and Cache true for
+  the transaction. Data is allocated by this routine, but never
+  freed.
+
+  @param[in] VariableName   Name of the Variable to track.
+  @param[in] VendorGuid     Guid of the Variable to track.
+  @param[in] Volatile       TRUE if volatile FALSE if non-volatile.
+  @param[in] Read           TRUE if GetVariable() was called.
+  @param[in] Write          TRUE if SetVariable() was called.
+  @param[in] Delete         TRUE if deleted via SetVariable().
+  @param[in] Cache          TRUE for a cache hit.
+
+**/
+VOID
+UpdateVariableInfo (
+  IN  CHAR16                  *VariableName,
+  IN  EFI_GUID                *VendorGuid,
+  IN  BOOLEAN                 Volatile,
+  IN  BOOLEAN                 Read,
+  IN  BOOLEAN                 Write,
+  IN  BOOLEAN                 Delete,
+  IN  BOOLEAN                 Cache
+  );
+
+#endif
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
index f32c9c2808..76536308e6 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
@@ -23,6 +23,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 **/
 
 #include "Variable.h"
+#include "VariableParsing.h"
 
 VARIABLE_MODULE_GLOBAL  *mVariableModuleGlobal;
 
@@ -92,131 +93,6 @@ AUTH_VAR_LIB_CONTEXT_IN mAuthContextIn = {
 
 AUTH_VAR_LIB_CONTEXT_OUT mAuthContextOut;
 
-/**
-  Routine used to track statistical information about variable usage.
-  The data is stored in the EFI system table so it can be accessed later.
-  VariableInfo.efi can dump out the table. Only Boot Services variable
-  accesses are tracked by this code. The PcdVariableCollectStatistics
-  build flag controls if this feature is enabled.
-
-  A read that hits in the cache will have Read and Cache true for
-  the transaction. Data is allocated by this routine, but never
-  freed.
-
-  @param[in] VariableName   Name of the Variable to track.
-  @param[in] VendorGuid     Guid of the Variable to track.
-  @param[in] Volatile       TRUE if volatile FALSE if non-volatile.
-  @param[in] Read           TRUE if GetVariable() was called.
-  @param[in] Write          TRUE if SetVariable() was called.
-  @param[in] Delete         TRUE if deleted via SetVariable().
-  @param[in] Cache          TRUE for a cache hit.
-
-**/
-VOID
-UpdateVariableInfo (
-  IN  CHAR16                  *VariableName,
-  IN  EFI_GUID                *VendorGuid,
-  IN  BOOLEAN                 Volatile,
-  IN  BOOLEAN                 Read,
-  IN  BOOLEAN                 Write,
-  IN  BOOLEAN                 Delete,
-  IN  BOOLEAN                 Cache
-  )
-{
-  VARIABLE_INFO_ENTRY   *Entry;
-
-  if (FeaturePcdGet (PcdVariableCollectStatistics)) {
-
-    if (AtRuntime ()) {
-      // Don't collect statistics at runtime.
-      return;
-    }
-
-    if (gVariableInfo == NULL) {
-      //
-      // On the first call allocate a entry and place a pointer to it in
-      // the EFI System Table.
-      //
-      gVariableInfo = AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY));
-      ASSERT (gVariableInfo != NULL);
-
-      CopyGuid (&gVariableInfo->VendorGuid, VendorGuid);
-      gVariableInfo->Name = AllocateZeroPool (StrSize (VariableName));
-      ASSERT (gVariableInfo->Name != NULL);
-      StrCpyS (gVariableInfo->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName);
-      gVariableInfo->Volatile = Volatile;
-    }
-
-
-    for (Entry = gVariableInfo; Entry != NULL; Entry = Entry->Next) {
-      if (CompareGuid (VendorGuid, &Entry->VendorGuid)) {
-        if (StrCmp (VariableName, Entry->Name) == 0) {
-          if (Read) {
-            Entry->ReadCount++;
-          }
-          if (Write) {
-            Entry->WriteCount++;
-          }
-          if (Delete) {
-            Entry->DeleteCount++;
-          }
-          if (Cache) {
-            Entry->CacheCount++;
-          }
-
-          return;
-        }
-      }
-
-      if (Entry->Next == NULL) {
-        //
-        // If the entry is not in the table add it.
-        // Next iteration of the loop will fill in the data.
-        //
-        Entry->Next = AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY));
-        ASSERT (Entry->Next != NULL);
-
-        CopyGuid (&Entry->Next->VendorGuid, VendorGuid);
-        Entry->Next->Name = AllocateZeroPool (StrSize (VariableName));
-        ASSERT (Entry->Next->Name != NULL);
-        StrCpyS (Entry->Next->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName);
-        Entry->Next->Volatile = Volatile;
-      }
-
-    }
-  }
-}
-
-
-/**
-
-  This code checks if variable header is valid or not.
-
-  @param Variable           Pointer to the Variable Header.
-  @param VariableStoreEnd   Pointer to the Variable Store End.
-
-  @retval TRUE              Variable header is valid.
-  @retval FALSE             Variable header is not valid.
-
-**/
-BOOLEAN
-IsValidVariableHeader (
-  IN  VARIABLE_HEADER       *Variable,
-  IN  VARIABLE_HEADER       *VariableStoreEnd
-  )
-{
-  if ((Variable == NULL) || (Variable >= VariableStoreEnd) || (Variable->StartId != VARIABLE_DATA)) {
-    //
-    // Variable is NULL or has reached the end of variable store,
-    // or the StartId is not correct.
-    //
-    return FALSE;
-  }
-
-  return TRUE;
-}
-
-
 /**
 
   This function writes data to the FWH at the correct LBA even if the LBAs
@@ -376,345 +252,6 @@ UpdateVariableStore (
   return EFI_SUCCESS;
 }
 
-
-/**
-
-  This code gets the current status of Variable Store.
-
-  @param VarStoreHeader  Pointer to the Variable Store Header.
-
-  @retval EfiRaw         Variable store status is raw.
-  @retval EfiValid       Variable store status is valid.
-  @retval EfiInvalid     Variable store status is invalid.
-
-**/
-VARIABLE_STORE_STATUS
-GetVariableStoreStatus (
-  IN VARIABLE_STORE_HEADER *VarStoreHeader
-  )
-{
-  if ((CompareGuid (&VarStoreHeader->Signature, &gEfiAuthenticatedVariableGuid) ||
-       CompareGuid (&VarStoreHeader->Signature, &gEfiVariableGuid)) &&
-      VarStoreHeader->Format == VARIABLE_STORE_FORMATTED &&
-      VarStoreHeader->State == VARIABLE_STORE_HEALTHY
-      ) {
-
-    return EfiValid;
-  } else if (((UINT32 *)(&VarStoreHeader->Signature))[0] == 0xffffffff &&
-             ((UINT32 *)(&VarStoreHeader->Signature))[1] == 0xffffffff &&
-             ((UINT32 *)(&VarStoreHeader->Signature))[2] == 0xffffffff &&
-             ((UINT32 *)(&VarStoreHeader->Signature))[3] == 0xffffffff &&
-             VarStoreHeader->Size == 0xffffffff &&
-             VarStoreHeader->Format == 0xff &&
-             VarStoreHeader->State == 0xff
-          ) {
-
-    return EfiRaw;
-  } else {
-    return EfiInvalid;
-  }
-}
-
-/**
-  This code gets the size of variable header.
-
-  @return Size of variable header in bytes in type UINTN.
-
-**/
-UINTN
-GetVariableHeaderSize (
-  VOID
-  )
-{
-  UINTN Value;
-
-  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
-    Value = sizeof (AUTHENTICATED_VARIABLE_HEADER);
-  } else {
-    Value = sizeof (VARIABLE_HEADER);
-  }
-
-  return Value;
-}
-
-/**
-
-  This code gets the size of name of variable.
-
-  @param Variable        Pointer to the Variable Header.
-
-  @return UINTN          Size of variable in bytes.
-
-**/
-UINTN
-NameSizeOfVariable (
-  IN  VARIABLE_HEADER   *Variable
-  )
-{
-  AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
-
-  AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
-  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
-    if (AuthVariable->State == (UINT8) (-1) ||
-       AuthVariable->DataSize == (UINT32) (-1) ||
-       AuthVariable->NameSize == (UINT32) (-1) ||
-       AuthVariable->Attributes == (UINT32) (-1)) {
-      return 0;
-    }
-    return (UINTN) AuthVariable->NameSize;
-  } else {
-    if (Variable->State == (UINT8) (-1) ||
-        Variable->DataSize == (UINT32) (-1) ||
-        Variable->NameSize == (UINT32) (-1) ||
-        Variable->Attributes == (UINT32) (-1)) {
-      return 0;
-    }
-    return (UINTN) Variable->NameSize;
-  }
-}
-
-/**
-  This code sets the size of name of variable.
-
-  @param[in] Variable   Pointer to the Variable Header.
-  @param[in] NameSize   Name size to set.
-
-**/
-VOID
-SetNameSizeOfVariable (
-  IN VARIABLE_HEADER    *Variable,
-  IN UINTN              NameSize
-  )
-{
-  AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
-
-  AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
-  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
-    AuthVariable->NameSize = (UINT32) NameSize;
-  } else {
-    Variable->NameSize = (UINT32) NameSize;
-  }
-}
-
-/**
-
-  This code gets the size of variable data.
-
-  @param Variable        Pointer to the Variable Header.
-
-  @return Size of variable in bytes.
-
-**/
-UINTN
-DataSizeOfVariable (
-  IN  VARIABLE_HEADER   *Variable
-  )
-{
-  AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
-
-  AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
-  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
-    if (AuthVariable->State == (UINT8) (-1) ||
-       AuthVariable->DataSize == (UINT32) (-1) ||
-       AuthVariable->NameSize == (UINT32) (-1) ||
-       AuthVariable->Attributes == (UINT32) (-1)) {
-      return 0;
-    }
-    return (UINTN) AuthVariable->DataSize;
-  } else {
-    if (Variable->State == (UINT8) (-1) ||
-        Variable->DataSize == (UINT32) (-1) ||
-        Variable->NameSize == (UINT32) (-1) ||
-        Variable->Attributes == (UINT32) (-1)) {
-      return 0;
-    }
-    return (UINTN) Variable->DataSize;
-  }
-}
-
-/**
-  This code sets the size of variable data.
-
-  @param[in] Variable   Pointer to the Variable Header.
-  @param[in] DataSize   Data size to set.
-
-**/
-VOID
-SetDataSizeOfVariable (
-  IN VARIABLE_HEADER    *Variable,
-  IN UINTN              DataSize
-  )
-{
-  AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
-
-  AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
-  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
-    AuthVariable->DataSize = (UINT32) DataSize;
-  } else {
-    Variable->DataSize = (UINT32) DataSize;
-  }
-}
-
-/**
-
-  This code gets the pointer to the variable name.
-
-  @param Variable        Pointer to the Variable Header.
-
-  @return Pointer to Variable Name which is Unicode encoding.
-
-**/
-CHAR16 *
-GetVariableNamePtr (
-  IN  VARIABLE_HEADER   *Variable
-  )
-{
-  return (CHAR16 *) ((UINTN) Variable + GetVariableHeaderSize ());
-}
-
-/**
-  This code gets the pointer to the variable guid.
-
-  @param Variable   Pointer to the Variable Header.
-
-  @return A EFI_GUID* pointer to Vendor Guid.
-
-**/
-EFI_GUID *
-GetVendorGuidPtr (
-  IN VARIABLE_HEADER    *Variable
-  )
-{
-  AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
-
-  AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
-  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
-    return &AuthVariable->VendorGuid;
-  } else {
-    return &Variable->VendorGuid;
-  }
-}
-
-/**
-
-  This code gets the pointer to the variable data.
-
-  @param Variable        Pointer to the Variable Header.
-
-  @return Pointer to Variable Data.
-
-**/
-UINT8 *
-GetVariableDataPtr (
-  IN  VARIABLE_HEADER   *Variable
-  )
-{
-  UINTN Value;
-
-  //
-  // Be careful about pad size for alignment.
-  //
-  Value =  (UINTN) GetVariableNamePtr (Variable);
-  Value += NameSizeOfVariable (Variable);
-  Value += GET_PAD_SIZE (NameSizeOfVariable (Variable));
-
-  return (UINT8 *) Value;
-}
-
-/**
-  This code gets the variable data offset related to variable header.
-
-  @param Variable        Pointer to the Variable Header.
-
-  @return Variable Data offset.
-
-**/
-UINTN
-GetVariableDataOffset (
-  IN  VARIABLE_HEADER   *Variable
-  )
-{
-  UINTN Value;
-
-  //
-  // Be careful about pad size for alignment
-  //
-  Value = GetVariableHeaderSize ();
-  Value += NameSizeOfVariable (Variable);
-  Value += GET_PAD_SIZE (NameSizeOfVariable (Variable));
-
-  return Value;
-}
-
-/**
-
-  This code gets the pointer to the next variable header.
-
-  @param Variable        Pointer to the Variable Header.
-
-  @return Pointer to next variable header.
-
-**/
-VARIABLE_HEADER *
-GetNextVariablePtr (
-  IN  VARIABLE_HEADER   *Variable
-  )
-{
-  UINTN Value;
-
-  Value =  (UINTN) GetVariableDataPtr (Variable);
-  Value += DataSizeOfVariable (Variable);
-  Value += GET_PAD_SIZE (DataSizeOfVariable (Variable));
-
-  //
-  // Be careful about pad size for alignment.
-  //
-  return (VARIABLE_HEADER *) HEADER_ALIGN (Value);
-}
-
-/**
-
-  Gets the pointer to the first variable header in given variable store area.
-
-  @param VarStoreHeader  Pointer to the Variable Store Header.
-
-  @return Pointer to the first variable header.
-
-**/
-VARIABLE_HEADER *
-GetStartPointer (
-  IN VARIABLE_STORE_HEADER       *VarStoreHeader
-  )
-{
-  //
-  // The start of variable store.
-  //
-  return (VARIABLE_HEADER *) HEADER_ALIGN (VarStoreHeader + 1);
-}
-
-/**
-
-  Gets the pointer to the end of the variable storage area.
-
-  This function gets pointer to the end of the variable storage
-  area, according to the input variable store header.
-
-  @param VarStoreHeader  Pointer to the Variable Store Header.
-
-  @return Pointer to the end of the variable storage area.
-
-**/
-VARIABLE_HEADER *
-GetEndPointer (
-  IN VARIABLE_STORE_HEADER       *VarStoreHeader
-  )
-{
-  //
-  // The end of variable store
-  //
-  return (VARIABLE_HEADER *) HEADER_ALIGN ((UINTN) VarStoreHeader + VarStoreHeader->Size);
-}
-
 /**
   Record variable error flag.
 
@@ -1228,75 +765,6 @@ Done:
   return Status;
 }
 
-/**
-  Find the variable in the specified variable store.
-
-  @param[in]       VariableName        Name of the variable to be found
-  @param[in]       VendorGuid          Vendor GUID to be found.
-  @param[in]       IgnoreRtCheck       Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute
-                                       check at runtime when searching variable.
-  @param[in, out]  PtrTrack            Variable Track Pointer structure that contains Variable Information.
-
-  @retval          EFI_SUCCESS         Variable found successfully
-  @retval          EFI_NOT_FOUND       Variable not found
-**/
-EFI_STATUS
-FindVariableEx (
-  IN     CHAR16                  *VariableName,
-  IN     EFI_GUID                *VendorGuid,
-  IN     BOOLEAN                 IgnoreRtCheck,
-  IN OUT VARIABLE_POINTER_TRACK  *PtrTrack
-  )
-{
-  VARIABLE_HEADER                *InDeletedVariable;
-  VOID                           *Point;
-
-  PtrTrack->InDeletedTransitionPtr = NULL;
-
-  //
-  // Find the variable by walk through HOB, volatile and non-volatile variable store.
-  //
-  InDeletedVariable  = NULL;
-
-  for ( PtrTrack->CurrPtr = PtrTrack->StartPtr
-      ; IsValidVariableHeader (PtrTrack->CurrPtr, PtrTrack->EndPtr)
-      ; PtrTrack->CurrPtr = GetNextVariablePtr (PtrTrack->CurrPtr)
-      ) {
-    if (PtrTrack->CurrPtr->State == VAR_ADDED ||
-        PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)
-       ) {
-      if (IgnoreRtCheck || !AtRuntime () || ((PtrTrack->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {
-        if (VariableName[0] == 0) {
-          if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
-            InDeletedVariable   = PtrTrack->CurrPtr;
-          } else {
-            PtrTrack->InDeletedTransitionPtr = InDeletedVariable;
-            return EFI_SUCCESS;
-          }
-        } else {
-          if (CompareGuid (VendorGuid, GetVendorGuidPtr (PtrTrack->CurrPtr))) {
-            Point = (VOID *) GetVariableNamePtr (PtrTrack->CurrPtr);
-
-            ASSERT (NameSizeOfVariable (PtrTrack->CurrPtr) != 0);
-            if (CompareMem (VariableName, Point, NameSizeOfVariable (PtrTrack->CurrPtr)) == 0) {
-              if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
-                InDeletedVariable     = PtrTrack->CurrPtr;
-              } else {
-                PtrTrack->InDeletedTransitionPtr = InDeletedVariable;
-                return EFI_SUCCESS;
-              }
-            }
-          }
-        }
-      }
-    }
-  }
-
-  PtrTrack->CurrPtr = InDeletedVariable;
-  return (PtrTrack->CurrPtr  == NULL) ? EFI_NOT_FOUND : EFI_SUCCESS;
-}
-
-
 /**
   Finds variable in storage blocks of volatile and non-volatile storage areas.
 
@@ -2078,38 +1546,6 @@ AutoUpdateLangVariable (
   }
 }
 
-/**
-  Compare two EFI_TIME data.
-
-
-  @param FirstTime           A pointer to the first EFI_TIME data.
-  @param SecondTime          A pointer to the second EFI_TIME data.
-
-  @retval  TRUE              The FirstTime is not later than the SecondTime.
-  @retval  FALSE             The FirstTime is later than the SecondTime.
-
-**/
-BOOLEAN
-VariableCompareTimeStampInternal (
-  IN EFI_TIME               *FirstTime,
-  IN EFI_TIME               *SecondTime
-  )
-{
-  if (FirstTime->Year != SecondTime->Year) {
-    return (BOOLEAN) (FirstTime->Year < SecondTime->Year);
-  } else if (FirstTime->Month != SecondTime->Month) {
-    return (BOOLEAN) (FirstTime->Month < SecondTime->Month);
-  } else if (FirstTime->Day != SecondTime->Day) {
-    return (BOOLEAN) (FirstTime->Day < SecondTime->Day);
-  } else if (FirstTime->Hour != SecondTime->Hour) {
-    return (BOOLEAN) (FirstTime->Hour < SecondTime->Hour);
-  } else if (FirstTime->Minute != SecondTime->Minute) {
-    return (BOOLEAN) (FirstTime->Minute < SecondTime->Minute);
-  }
-
-  return (BOOLEAN) (FirstTime->Second <= SecondTime->Second);
-}
-
 /**
   Update the variable region with Variable information. If EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS is set,
   index of associated public key is needed.
@@ -2885,166 +2321,6 @@ Done:
   return Status;
 }
 
-/**
-  This code Finds the Next available variable.
-
-  Caution: This function may receive untrusted input.
-  This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
-
-  @param[in]  VariableName  Pointer to variable name.
-  @param[in]  VendorGuid    Variable Vendor Guid.
-  @param[out] VariablePtr   Pointer to variable header address.
-
-  @retval EFI_SUCCESS           The function completed successfully.
-  @retval EFI_NOT_FOUND         The next variable was not found.
-  @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while VendorGuid is NULL.
-  @retval EFI_INVALID_PARAMETER The input values of VariableName and VendorGuid are not a name and
-                                GUID of an existing variable.
-
-**/
-EFI_STATUS
-EFIAPI
-VariableServiceGetNextVariableInternal (
-  IN  CHAR16                *VariableName,
-  IN  EFI_GUID              *VendorGuid,
-  OUT VARIABLE_HEADER       **VariablePtr
-  )
-{
-  VARIABLE_STORE_TYPE     Type;
-  VARIABLE_POINTER_TRACK  Variable;
-  VARIABLE_POINTER_TRACK  VariableInHob;
-  VARIABLE_POINTER_TRACK  VariablePtrTrack;
-  EFI_STATUS              Status;
-  VARIABLE_STORE_HEADER   *VariableStoreHeader[VariableStoreTypeMax];
-
-  Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
-  if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
-    //
-    // For VariableName is an empty string, FindVariable() will try to find and return
-    // the first qualified variable, and if FindVariable() returns error (EFI_NOT_FOUND)
-    // as no any variable is found, still go to return the error (EFI_NOT_FOUND).
-    //
-    if (VariableName[0] != 0) {
-      //
-      // For VariableName is not an empty string, and FindVariable() returns error as
-      // VariableName and VendorGuid are not a name and GUID of an existing variable,
-      // there is no way to get next variable, follow spec to return EFI_INVALID_PARAMETER.
-      //
-      Status = EFI_INVALID_PARAMETER;
-    }
-    goto Done;
-  }
-
-  if (VariableName[0] != 0) {
-    //
-    // If variable name is not NULL, get next variable.
-    //
-    Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
-  }
-
-  //
-  // 0: Volatile, 1: HOB, 2: Non-Volatile.
-  // The index and attributes mapping must be kept in this order as FindVariable
-  // makes use of this mapping to implement search algorithm.
-  //
-  VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
-  VariableStoreHeader[VariableStoreTypeHob]      = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
-  VariableStoreHeader[VariableStoreTypeNv]       = mNvVariableCache;
-
-  while (TRUE) {
-    //
-    // Switch from Volatile to HOB, to Non-Volatile.
-    //
-    while (!IsValidVariableHeader (Variable.CurrPtr, Variable.EndPtr)) {
-      //
-      // Find current storage index
-      //
-      for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {
-        if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) {
-          break;
-        }
-      }
-      ASSERT (Type < VariableStoreTypeMax);
-      //
-      // Switch to next storage
-      //
-      for (Type++; Type < VariableStoreTypeMax; Type++) {
-        if (VariableStoreHeader[Type] != NULL) {
-          break;
-        }
-      }
-      //
-      // Capture the case that
-      // 1. current storage is the last one, or
-      // 2. no further storage
-      //
-      if (Type == VariableStoreTypeMax) {
-        Status = EFI_NOT_FOUND;
-        goto Done;
-      }
-      Variable.StartPtr = GetStartPointer (VariableStoreHeader[Type]);
-      Variable.EndPtr   = GetEndPointer   (VariableStoreHeader[Type]);
-      Variable.CurrPtr  = Variable.StartPtr;
-    }
-
-    //
-    // Variable is found
-    //
-    if (Variable.CurrPtr->State == VAR_ADDED || Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
-      if (!AtRuntime () || ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {
-        if (Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
-          //
-          // If it is a IN_DELETED_TRANSITION variable,
-          // and there is also a same ADDED one at the same time,
-          // don't return it.
-          //
-          VariablePtrTrack.StartPtr = Variable.StartPtr;
-          VariablePtrTrack.EndPtr = Variable.EndPtr;
-          Status = FindVariableEx (
-                     GetVariableNamePtr (Variable.CurrPtr),
-                     GetVendorGuidPtr (Variable.CurrPtr),
-                     FALSE,
-                     &VariablePtrTrack
-                     );
-          if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State == VAR_ADDED) {
-            Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
-            continue;
-          }
-        }
-
-        //
-        // Don't return NV variable when HOB overrides it
-        //
-        if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) &&
-            (Variable.StartPtr == GetStartPointer (VariableStoreHeader[VariableStoreTypeNv]))
-           ) {
-          VariableInHob.StartPtr = GetStartPointer (VariableStoreHeader[VariableStoreTypeHob]);
-          VariableInHob.EndPtr   = GetEndPointer   (VariableStoreHeader[VariableStoreTypeHob]);
-          Status = FindVariableEx (
-                     GetVariableNamePtr (Variable.CurrPtr),
-                     GetVendorGuidPtr (Variable.CurrPtr),
-                     FALSE,
-                     &VariableInHob
-                     );
-          if (!EFI_ERROR (Status)) {
-            Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
-            continue;
-          }
-        }
-
-        *VariablePtr = Variable.CurrPtr;
-        Status = EFI_SUCCESS;
-        goto Done;
-      }
-    }
-
-    Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
-  }
-
-Done:
-  return Status;
-}
-
 /**
 
   This code Finds the Next available variable.
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c
index cb6fcebe2d..dc78f68fa9 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c
@@ -1,12 +1,13 @@
 /** @file
   Provides variable driver extended services.
 
-Copyright (c) 2015, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2015 - 2019, Intel Corporation. All rights reserved.<BR>
 SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
 
 #include "Variable.h"
+#include "VariableParsing.h"
 
 /**
   Finds variable in storage blocks of volatile and non-volatile storage areas.
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c
new file mode 100644
index 0000000000..5698a1a5e4
--- /dev/null
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c
@@ -0,0 +1,731 @@
+/** @file
+  Functions in this module are associated with variable parsing operations and
+  are intended to be usable across variable driver source files.
+
+Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "VariableParsing.h"
+
+/**
+
+  This code checks if variable header is valid or not.
+
+  @param[in] Variable           Pointer to the Variable Header.
+  @param[in] VariableStoreEnd   Pointer to the Variable Store End.
+
+  @retval TRUE              Variable header is valid.
+  @retval FALSE             Variable header is not valid.
+
+**/
+BOOLEAN
+IsValidVariableHeader (
+  IN  VARIABLE_HEADER       *Variable,
+  IN  VARIABLE_HEADER       *VariableStoreEnd
+  )
+{
+  if ((Variable == NULL) || (Variable >= VariableStoreEnd) || (Variable->StartId != VARIABLE_DATA)) {
+    //
+    // Variable is NULL or has reached the end of variable store,
+    // or the StartId is not correct.
+    //
+    return FALSE;
+  }
+
+  return TRUE;
+}
+
+/**
+
+  This code gets the current status of Variable Store.
+
+  @param[in] VarStoreHeader  Pointer to the Variable Store Header.
+
+  @retval EfiRaw         Variable store status is raw.
+  @retval EfiValid       Variable store status is valid.
+  @retval EfiInvalid     Variable store status is invalid.
+
+**/
+VARIABLE_STORE_STATUS
+GetVariableStoreStatus (
+  IN VARIABLE_STORE_HEADER *VarStoreHeader
+  )
+{
+  if ((CompareGuid (&VarStoreHeader->Signature, &gEfiAuthenticatedVariableGuid) ||
+       CompareGuid (&VarStoreHeader->Signature, &gEfiVariableGuid)) &&
+      VarStoreHeader->Format == VARIABLE_STORE_FORMATTED &&
+      VarStoreHeader->State == VARIABLE_STORE_HEALTHY
+      ) {
+
+    return EfiValid;
+  } else if (((UINT32 *)(&VarStoreHeader->Signature))[0] == 0xffffffff &&
+             ((UINT32 *)(&VarStoreHeader->Signature))[1] == 0xffffffff &&
+             ((UINT32 *)(&VarStoreHeader->Signature))[2] == 0xffffffff &&
+             ((UINT32 *)(&VarStoreHeader->Signature))[3] == 0xffffffff &&
+             VarStoreHeader->Size == 0xffffffff &&
+             VarStoreHeader->Format == 0xff &&
+             VarStoreHeader->State == 0xff
+          ) {
+
+    return EfiRaw;
+  } else {
+    return EfiInvalid;
+  }
+}
+
+/**
+  This code gets the size of variable header.
+
+  @return Size of variable header in bytes in type UINTN.
+
+**/
+UINTN
+GetVariableHeaderSize (
+  VOID
+  )
+{
+  UINTN Value;
+
+  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
+    Value = sizeof (AUTHENTICATED_VARIABLE_HEADER);
+  } else {
+    Value = sizeof (VARIABLE_HEADER);
+  }
+
+  return Value;
+}
+
+/**
+
+  This code gets the size of name of variable.
+
+  @param Variable        Pointer to the Variable Header.
+
+  @return UINTN          Size of variable in bytes.
+
+**/
+UINTN
+NameSizeOfVariable (
+  IN  VARIABLE_HEADER   *Variable
+  )
+{
+  AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
+
+  AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
+  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
+    if (AuthVariable->State == (UINT8) (-1) ||
+       AuthVariable->DataSize == (UINT32) (-1) ||
+       AuthVariable->NameSize == (UINT32) (-1) ||
+       AuthVariable->Attributes == (UINT32) (-1)) {
+      return 0;
+    }
+    return (UINTN) AuthVariable->NameSize;
+  } else {
+    if (Variable->State == (UINT8) (-1) ||
+        Variable->DataSize == (UINT32) (-1) ||
+        Variable->NameSize == (UINT32) (-1) ||
+        Variable->Attributes == (UINT32) (-1)) {
+      return 0;
+    }
+    return (UINTN) Variable->NameSize;
+  }
+}
+
+/**
+  This code sets the size of name of variable.
+
+  @param[in] Variable   Pointer to the Variable Header.
+  @param[in] NameSize   Name size to set.
+
+**/
+VOID
+SetNameSizeOfVariable (
+  IN VARIABLE_HEADER    *Variable,
+  IN UINTN              NameSize
+  )
+{
+  AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
+
+  AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
+  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
+    AuthVariable->NameSize = (UINT32) NameSize;
+  } else {
+    Variable->NameSize = (UINT32) NameSize;
+  }
+}
+
+/**
+
+  This code gets the size of variable data.
+
+  @param Variable        Pointer to the Variable Header.
+
+  @return Size of variable in bytes.
+
+**/
+UINTN
+DataSizeOfVariable (
+  IN  VARIABLE_HEADER   *Variable
+  )
+{
+  AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
+
+  AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
+  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
+    if (AuthVariable->State == (UINT8) (-1) ||
+       AuthVariable->DataSize == (UINT32) (-1) ||
+       AuthVariable->NameSize == (UINT32) (-1) ||
+       AuthVariable->Attributes == (UINT32) (-1)) {
+      return 0;
+    }
+    return (UINTN) AuthVariable->DataSize;
+  } else {
+    if (Variable->State == (UINT8) (-1) ||
+        Variable->DataSize == (UINT32) (-1) ||
+        Variable->NameSize == (UINT32) (-1) ||
+        Variable->Attributes == (UINT32) (-1)) {
+      return 0;
+    }
+    return (UINTN) Variable->DataSize;
+  }
+}
+
+/**
+  This code sets the size of variable data.
+
+  @param[in] Variable   Pointer to the Variable Header.
+  @param[in] DataSize   Data size to set.
+
+**/
+VOID
+SetDataSizeOfVariable (
+  IN VARIABLE_HEADER    *Variable,
+  IN UINTN              DataSize
+  )
+{
+  AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
+
+  AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
+  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
+    AuthVariable->DataSize = (UINT32) DataSize;
+  } else {
+    Variable->DataSize = (UINT32) DataSize;
+  }
+}
+
+/**
+
+  This code gets the pointer to the variable name.
+
+  @param Variable        Pointer to the Variable Header.
+
+  @return Pointer to Variable Name which is Unicode encoding.
+
+**/
+CHAR16 *
+GetVariableNamePtr (
+  IN  VARIABLE_HEADER   *Variable
+  )
+{
+  return (CHAR16 *) ((UINTN) Variable + GetVariableHeaderSize ());
+}
+
+/**
+  This code gets the pointer to the variable guid.
+
+  @param Variable   Pointer to the Variable Header.
+
+  @return A EFI_GUID* pointer to Vendor Guid.
+
+**/
+EFI_GUID *
+GetVendorGuidPtr (
+  IN VARIABLE_HEADER    *Variable
+  )
+{
+  AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
+
+  AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
+  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
+    return &AuthVariable->VendorGuid;
+  } else {
+    return &Variable->VendorGuid;
+  }
+}
+
+/**
+
+  This code gets the pointer to the variable data.
+
+  @param Variable        Pointer to the Variable Header.
+
+  @return Pointer to Variable Data.
+
+**/
+UINT8 *
+GetVariableDataPtr (
+  IN  VARIABLE_HEADER   *Variable
+  )
+{
+  UINTN Value;
+
+  //
+  // Be careful about pad size for alignment.
+  //
+  Value =  (UINTN) GetVariableNamePtr (Variable);
+  Value += NameSizeOfVariable (Variable);
+  Value += GET_PAD_SIZE (NameSizeOfVariable (Variable));
+
+  return (UINT8 *) Value;
+}
+
+/**
+  This code gets the variable data offset related to variable header.
+
+  @param Variable        Pointer to the Variable Header.
+
+  @return Variable Data offset.
+
+**/
+UINTN
+GetVariableDataOffset (
+  IN  VARIABLE_HEADER   *Variable
+  )
+{
+  UINTN Value;
+
+  //
+  // Be careful about pad size for alignment
+  //
+  Value = GetVariableHeaderSize ();
+  Value += NameSizeOfVariable (Variable);
+  Value += GET_PAD_SIZE (NameSizeOfVariable (Variable));
+
+  return Value;
+}
+
+/**
+
+  This code gets the pointer to the next variable header.
+
+  @param Variable        Pointer to the Variable Header.
+
+  @return Pointer to next variable header.
+
+**/
+VARIABLE_HEADER *
+GetNextVariablePtr (
+  IN  VARIABLE_HEADER   *Variable
+  )
+{
+  UINTN Value;
+
+  Value =  (UINTN) GetVariableDataPtr (Variable);
+  Value += DataSizeOfVariable (Variable);
+  Value += GET_PAD_SIZE (DataSizeOfVariable (Variable));
+
+  //
+  // Be careful about pad size for alignment.
+  //
+  return (VARIABLE_HEADER *) HEADER_ALIGN (Value);
+}
+
+/**
+
+  Gets the pointer to the first variable header in given variable store area.
+
+  @param[in] VarStoreHeader  Pointer to the Variable Store Header.
+
+  @return Pointer to the first variable header.
+
+**/
+VARIABLE_HEADER *
+GetStartPointer (
+  IN VARIABLE_STORE_HEADER       *VarStoreHeader
+  )
+{
+  //
+  // The start of variable store.
+  //
+  return (VARIABLE_HEADER *) HEADER_ALIGN (VarStoreHeader + 1);
+}
+
+/**
+
+  Gets the pointer to the end of the variable storage area.
+
+  This function gets pointer to the end of the variable storage
+  area, according to the input variable store header.
+
+  @param[in] VarStoreHeader  Pointer to the Variable Store Header.
+
+  @return Pointer to the end of the variable storage area.
+
+**/
+VARIABLE_HEADER *
+GetEndPointer (
+  IN VARIABLE_STORE_HEADER       *VarStoreHeader
+  )
+{
+  //
+  // The end of variable store
+  //
+  return (VARIABLE_HEADER *) HEADER_ALIGN ((UINTN) VarStoreHeader + VarStoreHeader->Size);
+}
+
+/**
+  Compare two EFI_TIME data.
+
+
+  @param[in] FirstTime       A pointer to the first EFI_TIME data.
+  @param[in] SecondTime      A pointer to the second EFI_TIME data.
+
+  @retval  TRUE              The FirstTime is not later than the SecondTime.
+  @retval  FALSE             The FirstTime is later than the SecondTime.
+
+**/
+BOOLEAN
+VariableCompareTimeStampInternal (
+  IN EFI_TIME               *FirstTime,
+  IN EFI_TIME               *SecondTime
+  )
+{
+  if (FirstTime->Year != SecondTime->Year) {
+    return (BOOLEAN) (FirstTime->Year < SecondTime->Year);
+  } else if (FirstTime->Month != SecondTime->Month) {
+    return (BOOLEAN) (FirstTime->Month < SecondTime->Month);
+  } else if (FirstTime->Day != SecondTime->Day) {
+    return (BOOLEAN) (FirstTime->Day < SecondTime->Day);
+  } else if (FirstTime->Hour != SecondTime->Hour) {
+    return (BOOLEAN) (FirstTime->Hour < SecondTime->Hour);
+  } else if (FirstTime->Minute != SecondTime->Minute) {
+    return (BOOLEAN) (FirstTime->Minute < SecondTime->Minute);
+  }
+
+  return (BOOLEAN) (FirstTime->Second <= SecondTime->Second);
+}
+
+/**
+  Find the variable in the specified variable store.
+
+  @param[in]       VariableName        Name of the variable to be found
+  @param[in]       VendorGuid          Vendor GUID to be found.
+  @param[in]       IgnoreRtCheck       Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute
+                                       check at runtime when searching variable.
+  @param[in, out]  PtrTrack            Variable Track Pointer structure that contains Variable Information.
+
+  @retval          EFI_SUCCESS         Variable found successfully
+  @retval          EFI_NOT_FOUND       Variable not found
+**/
+EFI_STATUS
+FindVariableEx (
+  IN     CHAR16                  *VariableName,
+  IN     EFI_GUID                *VendorGuid,
+  IN     BOOLEAN                 IgnoreRtCheck,
+  IN OUT VARIABLE_POINTER_TRACK  *PtrTrack
+  )
+{
+  VARIABLE_HEADER                *InDeletedVariable;
+  VOID                           *Point;
+
+  PtrTrack->InDeletedTransitionPtr = NULL;
+
+  //
+  // Find the variable by walk through HOB, volatile and non-volatile variable store.
+  //
+  InDeletedVariable  = NULL;
+
+  for ( PtrTrack->CurrPtr = PtrTrack->StartPtr
+      ; IsValidVariableHeader (PtrTrack->CurrPtr, PtrTrack->EndPtr)
+      ; PtrTrack->CurrPtr = GetNextVariablePtr (PtrTrack->CurrPtr)
+      ) {
+    if (PtrTrack->CurrPtr->State == VAR_ADDED ||
+        PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)
+       ) {
+      if (IgnoreRtCheck || !AtRuntime () || ((PtrTrack->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {
+        if (VariableName[0] == 0) {
+          if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+            InDeletedVariable   = PtrTrack->CurrPtr;
+          } else {
+            PtrTrack->InDeletedTransitionPtr = InDeletedVariable;
+            return EFI_SUCCESS;
+          }
+        } else {
+          if (CompareGuid (VendorGuid, GetVendorGuidPtr (PtrTrack->CurrPtr))) {
+            Point = (VOID *) GetVariableNamePtr (PtrTrack->CurrPtr);
+
+            ASSERT (NameSizeOfVariable (PtrTrack->CurrPtr) != 0);
+            if (CompareMem (VariableName, Point, NameSizeOfVariable (PtrTrack->CurrPtr)) == 0) {
+              if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+                InDeletedVariable     = PtrTrack->CurrPtr;
+              } else {
+                PtrTrack->InDeletedTransitionPtr = InDeletedVariable;
+                return EFI_SUCCESS;
+              }
+            }
+          }
+        }
+      }
+    }
+  }
+
+  PtrTrack->CurrPtr = InDeletedVariable;
+  return (PtrTrack->CurrPtr  == NULL) ? EFI_NOT_FOUND : EFI_SUCCESS;
+}
+
+/**
+  This code Finds the Next available variable.
+
+  Caution: This function may receive untrusted input.
+  This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
+
+  @param[in]  VariableName  Pointer to variable name.
+  @param[in]  VendorGuid    Variable Vendor Guid.
+  @param[out] VariablePtr   Pointer to variable header address.
+
+  @retval EFI_SUCCESS           The function completed successfully.
+  @retval EFI_NOT_FOUND         The next variable was not found.
+  @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while VendorGuid is NULL.
+  @retval EFI_INVALID_PARAMETER The input values of VariableName and VendorGuid are not a name and
+                                GUID of an existing variable.
+
+**/
+EFI_STATUS
+EFIAPI
+VariableServiceGetNextVariableInternal (
+  IN  CHAR16                *VariableName,
+  IN  EFI_GUID              *VendorGuid,
+  OUT VARIABLE_HEADER       **VariablePtr
+  )
+{
+  VARIABLE_STORE_TYPE     Type;
+  VARIABLE_POINTER_TRACK  Variable;
+  VARIABLE_POINTER_TRACK  VariableInHob;
+  VARIABLE_POINTER_TRACK  VariablePtrTrack;
+  EFI_STATUS              Status;
+  VARIABLE_STORE_HEADER   *VariableStoreHeader[VariableStoreTypeMax];
+
+  Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
+  if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
+    //
+    // For VariableName is an empty string, FindVariable() will try to find and return
+    // the first qualified variable, and if FindVariable() returns error (EFI_NOT_FOUND)
+    // as no any variable is found, still go to return the error (EFI_NOT_FOUND).
+    //
+    if (VariableName[0] != 0) {
+      //
+      // For VariableName is not an empty string, and FindVariable() returns error as
+      // VariableName and VendorGuid are not a name and GUID of an existing variable,
+      // there is no way to get next variable, follow spec to return EFI_INVALID_PARAMETER.
+      //
+      Status = EFI_INVALID_PARAMETER;
+    }
+    goto Done;
+  }
+
+  if (VariableName[0] != 0) {
+    //
+    // If variable name is not NULL, get next variable.
+    //
+    Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
+  }
+
+  //
+  // 0: Volatile, 1: HOB, 2: Non-Volatile.
+  // The index and attributes mapping must be kept in this order as FindVariable
+  // makes use of this mapping to implement search algorithm.
+  //
+  VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
+  VariableStoreHeader[VariableStoreTypeHob]      = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
+  VariableStoreHeader[VariableStoreTypeNv]       = mNvVariableCache;
+
+  while (TRUE) {
+    //
+    // Switch from Volatile to HOB, to Non-Volatile.
+    //
+    while (!IsValidVariableHeader (Variable.CurrPtr, Variable.EndPtr)) {
+      //
+      // Find current storage index
+      //
+      for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {
+        if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) {
+          break;
+        }
+      }
+      ASSERT (Type < VariableStoreTypeMax);
+      //
+      // Switch to next storage
+      //
+      for (Type++; Type < VariableStoreTypeMax; Type++) {
+        if (VariableStoreHeader[Type] != NULL) {
+          break;
+        }
+      }
+      //
+      // Capture the case that
+      // 1. current storage is the last one, or
+      // 2. no further storage
+      //
+      if (Type == VariableStoreTypeMax) {
+        Status = EFI_NOT_FOUND;
+        goto Done;
+      }
+      Variable.StartPtr = GetStartPointer (VariableStoreHeader[Type]);
+      Variable.EndPtr   = GetEndPointer   (VariableStoreHeader[Type]);
+      Variable.CurrPtr  = Variable.StartPtr;
+    }
+
+    //
+    // Variable is found
+    //
+    if (Variable.CurrPtr->State == VAR_ADDED || Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+      if (!AtRuntime () || ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {
+        if (Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+          //
+          // If it is a IN_DELETED_TRANSITION variable,
+          // and there is also a same ADDED one at the same time,
+          // don't return it.
+          //
+          VariablePtrTrack.StartPtr = Variable.StartPtr;
+          VariablePtrTrack.EndPtr = Variable.EndPtr;
+          Status = FindVariableEx (
+                     GetVariableNamePtr (Variable.CurrPtr),
+                     GetVendorGuidPtr (Variable.CurrPtr),
+                     FALSE,
+                     &VariablePtrTrack
+                     );
+          if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State == VAR_ADDED) {
+            Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
+            continue;
+          }
+        }
+
+        //
+        // Don't return NV variable when HOB overrides it
+        //
+        if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) &&
+            (Variable.StartPtr == GetStartPointer (VariableStoreHeader[VariableStoreTypeNv]))
+           ) {
+          VariableInHob.StartPtr = GetStartPointer (VariableStoreHeader[VariableStoreTypeHob]);
+          VariableInHob.EndPtr   = GetEndPointer   (VariableStoreHeader[VariableStoreTypeHob]);
+          Status = FindVariableEx (
+                     GetVariableNamePtr (Variable.CurrPtr),
+                     GetVendorGuidPtr (Variable.CurrPtr),
+                     FALSE,
+                     &VariableInHob
+                     );
+          if (!EFI_ERROR (Status)) {
+            Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
+            continue;
+          }
+        }
+
+        *VariablePtr = Variable.CurrPtr;
+        Status = EFI_SUCCESS;
+        goto Done;
+      }
+    }
+
+    Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
+  }
+
+Done:
+  return Status;
+}
+
+/**
+  Routine used to track statistical information about variable usage.
+  The data is stored in the EFI system table so it can be accessed later.
+  VariableInfo.efi can dump out the table. Only Boot Services variable
+  accesses are tracked by this code. The PcdVariableCollectStatistics
+  build flag controls if this feature is enabled.
+
+  A read that hits in the cache will have Read and Cache true for
+  the transaction. Data is allocated by this routine, but never
+  freed.
+
+  @param[in] VariableName   Name of the Variable to track.
+  @param[in] VendorGuid     Guid of the Variable to track.
+  @param[in] Volatile       TRUE if volatile FALSE if non-volatile.
+  @param[in] Read           TRUE if GetVariable() was called.
+  @param[in] Write          TRUE if SetVariable() was called.
+  @param[in] Delete         TRUE if deleted via SetVariable().
+  @param[in] Cache          TRUE for a cache hit.
+
+**/
+VOID
+UpdateVariableInfo (
+  IN  CHAR16                  *VariableName,
+  IN  EFI_GUID                *VendorGuid,
+  IN  BOOLEAN                 Volatile,
+  IN  BOOLEAN                 Read,
+  IN  BOOLEAN                 Write,
+  IN  BOOLEAN                 Delete,
+  IN  BOOLEAN                 Cache
+  )
+{
+  VARIABLE_INFO_ENTRY   *Entry;
+
+  if (FeaturePcdGet (PcdVariableCollectStatistics)) {
+
+    if (AtRuntime ()) {
+      // Don't collect statistics at runtime.
+      return;
+    }
+
+    if (gVariableInfo == NULL) {
+      //
+      // On the first call allocate a entry and place a pointer to it in
+      // the EFI System Table.
+      //
+      gVariableInfo = AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY));
+      ASSERT (gVariableInfo != NULL);
+
+      CopyGuid (&gVariableInfo->VendorGuid, VendorGuid);
+      gVariableInfo->Name = AllocateZeroPool (StrSize (VariableName));
+      ASSERT (gVariableInfo->Name != NULL);
+      StrCpyS (gVariableInfo->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName);
+      gVariableInfo->Volatile = Volatile;
+    }
+
+
+    for (Entry = gVariableInfo; Entry != NULL; Entry = Entry->Next) {
+      if (CompareGuid (VendorGuid, &Entry->VendorGuid)) {
+        if (StrCmp (VariableName, Entry->Name) == 0) {
+          if (Read) {
+            Entry->ReadCount++;
+          }
+          if (Write) {
+            Entry->WriteCount++;
+          }
+          if (Delete) {
+            Entry->DeleteCount++;
+          }
+          if (Cache) {
+            Entry->CacheCount++;
+          }
+
+          return;
+        }
+      }
+
+      if (Entry->Next == NULL) {
+        //
+        // If the entry is not in the table add it.
+        // Next iteration of the loop will fill in the data.
+        //
+        Entry->Next = AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY));
+        ASSERT (Entry->Next != NULL);
+
+        CopyGuid (&Entry->Next->VendorGuid, VendorGuid);
+        Entry->Next->Name = AllocateZeroPool (StrSize (VariableName));
+        ASSERT (Entry->Next->Name != NULL);
+        StrCpyS (Entry->Next->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName);
+        Entry->Next->Volatile = Volatile;
+      }
+
+    }
+  }
+}
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c
index ec463d063e..ce409f22a3 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c
@@ -30,6 +30,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 
 #include <Guid/SmmVariableCommon.h>
 #include "Variable.h"
+#include "VariableParsing.h"
 
 BOOLEAN                                              mAtRuntime              = FALSE;
 UINT8                                                *mVariableBufferPayload = NULL;
-- 
2.16.2.windows.1


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [PATCH V7 02/10] MdeModulePkg/Variable: Parameterize GetNextVariableInternal () stores
  2019-11-01 17:34 [PATCH V7 00/10] UEFI Variable SMI Reduction Kubacki, Michael A
  2019-11-01 17:34 ` [PATCH V7 01/10] MdeModulePkg/Variable: Consolidate common parsing functions Kubacki, Michael A
@ 2019-11-01 17:34 ` Kubacki, Michael A
  2019-11-01 17:34 ` [PATCH V7 03/10] MdeModulePkg/Variable: Parameterize VARIABLE_INFO_ENTRY buffer Kubacki, Michael A
                   ` (8 subsequent siblings)
  10 siblings, 0 replies; 14+ messages in thread
From: Kubacki, Michael A @ 2019-11-01 17:34 UTC (permalink / raw)
  To: devel
  Cc: Dandan Bi, Ard Biesheuvel, Eric Dong, Laszlo Ersek, Liming Gao,
	Michael D Kinney, Ray Ni, Jian J Wang, Hao A Wu, Jiewen Yao

The majority of logic related to GetNextVariableName () is currently
implemented in VariableServiceGetNextVariableInternal (). The list
of variable stores to search for the given variable name and variable
GUID is defined in the function body. This change adds a new parameter
so that the caller must pass in the list of variable stores to be used
in the variable search.

Cc: Dandan Bi <dandan.bi@intel.com>
Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Eric Dong <eric.dong@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Cc: Liming Gao <liming.gao@intel.com>
Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Hao A Wu <hao.a.wu@intel.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Signed-off-by: Michael Kubacki <michael.a.kubacki@intel.com>
---
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h | 13 ++--
 MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c        | 12 ++-
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c   |  6 ++
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c | 82 ++++++++++++--------
 4 files changed, 73 insertions(+), 40 deletions(-)

diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h
index b0d7f76bd8..6555316f52 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h
@@ -248,18 +248,20 @@ FindVariableEx (
   );
 
 /**
-  This code Finds the Next available variable.
+  This code finds the next available variable.
 
   Caution: This function may receive untrusted input.
   This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
 
-  @param[in]  VariableName  Pointer to variable name.
-  @param[in]  VendorGuid    Variable Vendor Guid.
-  @param[out] VariablePtr   Pointer to variable header address.
+  @param[in]  VariableName      Pointer to variable name.
+  @param[in]  VendorGuid        Variable Vendor Guid.
+  @param[in]  VariableStoreList A list of variable stores that should be used to get the next variable.
+                                The maximum number of entries is the max value of VARIABLE_STORE_TYPE.
+  @param[out] VariablePtr       Pointer to variable header address.
 
   @retval EFI_SUCCESS           The function completed successfully.
   @retval EFI_NOT_FOUND         The next variable was not found.
-  @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while VendorGuid is NULL.
+  @retval EFI_INVALID_PARAMETER If VariableName is nt an empty string, while VendorGuid is NULL.
   @retval EFI_INVALID_PARAMETER The input values of VariableName and VendorGuid are not a name and
                                 GUID of an existing variable.
 
@@ -269,6 +271,7 @@ EFIAPI
 VariableServiceGetNextVariableInternal (
   IN  CHAR16                *VariableName,
   IN  EFI_GUID              *VendorGuid,
+  IN  VARIABLE_STORE_HEADER **VariableStoreList,
   OUT VARIABLE_HEADER       **VariablePtr
   );
 
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
index 76536308e6..70af86db24 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
@@ -2358,6 +2358,7 @@ VariableServiceGetNextVariableName (
   UINTN                   MaxLen;
   UINTN                   VarNameSize;
   VARIABLE_HEADER         *VariablePtr;
+  VARIABLE_STORE_HEADER   *VariableStoreHeader[VariableStoreTypeMax];
 
   if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {
     return EFI_INVALID_PARAMETER;
@@ -2377,7 +2378,16 @@ VariableServiceGetNextVariableName (
 
   AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);
 
-  Status = VariableServiceGetNextVariableInternal (VariableName, VendorGuid, &VariablePtr);
+  //
+  // 0: Volatile, 1: HOB, 2: Non-Volatile.
+  // The index and attributes mapping must be kept in this order as FindVariable
+  // makes use of this mapping to implement search algorithm.
+  //
+  VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
+  VariableStoreHeader[VariableStoreTypeHob]      = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
+  VariableStoreHeader[VariableStoreTypeNv]       = mNvVariableCache;
+
+  Status = VariableServiceGetNextVariableInternal (VariableName, VendorGuid, VariableStoreHeader, &VariablePtr);
   if (!EFI_ERROR (Status)) {
     VarNameSize = NameSizeOfVariable (VariablePtr);
     ASSERT (VarNameSize != 0);
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c
index dc78f68fa9..c787ddba5b 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c
@@ -98,10 +98,16 @@ VariableExLibFindNextVariable (
   EFI_STATUS                    Status;
   VARIABLE_HEADER               *VariablePtr;
   AUTHENTICATED_VARIABLE_HEADER *AuthVariablePtr;
+  VARIABLE_STORE_HEADER         *VariableStoreHeader[VariableStoreTypeMax];
+
+  VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
+  VariableStoreHeader[VariableStoreTypeHob]      = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
+  VariableStoreHeader[VariableStoreTypeNv]       = mNvVariableCache;
 
   Status = VariableServiceGetNextVariableInternal (
              VariableName,
              VendorGuid,
+             VariableStoreHeader,
              &VariablePtr
              );
   if (EFI_ERROR (Status)) {
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c
index 5698a1a5e4..d6bb916e68 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c
@@ -476,14 +476,16 @@ FindVariableEx (
 }
 
 /**
-  This code Finds the Next available variable.
+  This code finds the next available variable.
 
   Caution: This function may receive untrusted input.
   This function may be invoked in SMM mode. This function will do basic validation, before parse the data.
 
-  @param[in]  VariableName  Pointer to variable name.
-  @param[in]  VendorGuid    Variable Vendor Guid.
-  @param[out] VariablePtr   Pointer to variable header address.
+  @param[in]  VariableName      Pointer to variable name.
+  @param[in]  VendorGuid        Variable Vendor Guid.
+  @param[in]  VariableStoreList A list of variable stores that should be used to get the next variable.
+                                The maximum number of entries is the max value of VARIABLE_STORE_TYPE.
+  @param[out] VariablePtr       Pointer to variable header address.
 
   @retval EFI_SUCCESS           The function completed successfully.
   @retval EFI_NOT_FOUND         The next variable was not found.
@@ -497,26 +499,47 @@ EFIAPI
 VariableServiceGetNextVariableInternal (
   IN  CHAR16                *VariableName,
   IN  EFI_GUID              *VendorGuid,
+  IN  VARIABLE_STORE_HEADER **VariableStoreList,
   OUT VARIABLE_HEADER       **VariablePtr
   )
 {
-  VARIABLE_STORE_TYPE     Type;
+  EFI_STATUS              Status;
+  VARIABLE_STORE_TYPE     StoreType;
   VARIABLE_POINTER_TRACK  Variable;
   VARIABLE_POINTER_TRACK  VariableInHob;
   VARIABLE_POINTER_TRACK  VariablePtrTrack;
-  EFI_STATUS              Status;
-  VARIABLE_STORE_HEADER   *VariableStoreHeader[VariableStoreTypeMax];
 
-  Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
+  Status = EFI_NOT_FOUND;
+
+  if (VariableStoreList == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  // Check if the variable exists in the given variable store list
+  for (StoreType = (VARIABLE_STORE_TYPE) 0; StoreType < VariableStoreTypeMax; StoreType++) {
+    if (VariableStoreList[StoreType] == NULL) {
+      continue;
+    }
+
+    Variable.StartPtr = GetStartPointer (VariableStoreList[StoreType]);
+    Variable.EndPtr   = GetEndPointer   (VariableStoreList[StoreType]);
+    Variable.Volatile = (BOOLEAN) (StoreType == VariableStoreTypeVolatile);
+
+    Status = FindVariableEx (VariableName, VendorGuid, FALSE, &Variable);
+    if (!EFI_ERROR (Status)) {
+      break;
+    }
+  }
+
   if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {
     //
-    // For VariableName is an empty string, FindVariable() will try to find and return
-    // the first qualified variable, and if FindVariable() returns error (EFI_NOT_FOUND)
+    // For VariableName is an empty string, FindVariableEx() will try to find and return
+    // the first qualified variable, and if FindVariableEx() returns error (EFI_NOT_FOUND)
     // as no any variable is found, still go to return the error (EFI_NOT_FOUND).
     //
     if (VariableName[0] != 0) {
       //
-      // For VariableName is not an empty string, and FindVariable() returns error as
+      // For VariableName is not an empty string, and FindVariableEx() returns error as
       // VariableName and VendorGuid are not a name and GUID of an existing variable,
       // there is no way to get next variable, follow spec to return EFI_INVALID_PARAMETER.
       //
@@ -527,39 +550,30 @@ VariableServiceGetNextVariableInternal (
 
   if (VariableName[0] != 0) {
     //
-    // If variable name is not NULL, get next variable.
+    // If variable name is not empty, get next variable.
     //
     Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
   }
 
-  //
-  // 0: Volatile, 1: HOB, 2: Non-Volatile.
-  // The index and attributes mapping must be kept in this order as FindVariable
-  // makes use of this mapping to implement search algorithm.
-  //
-  VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
-  VariableStoreHeader[VariableStoreTypeHob]      = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
-  VariableStoreHeader[VariableStoreTypeNv]       = mNvVariableCache;
-
   while (TRUE) {
     //
-    // Switch from Volatile to HOB, to Non-Volatile.
+    // Switch to the next variable store if needed
     //
     while (!IsValidVariableHeader (Variable.CurrPtr, Variable.EndPtr)) {
       //
       // Find current storage index
       //
-      for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {
-        if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) {
+      for (StoreType = (VARIABLE_STORE_TYPE) 0; StoreType < VariableStoreTypeMax; StoreType++) {
+        if ((VariableStoreList[StoreType] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreList[StoreType]))) {
           break;
         }
       }
-      ASSERT (Type < VariableStoreTypeMax);
+      ASSERT (StoreType < VariableStoreTypeMax);
       //
       // Switch to next storage
       //
-      for (Type++; Type < VariableStoreTypeMax; Type++) {
-        if (VariableStoreHeader[Type] != NULL) {
+      for (StoreType++; StoreType < VariableStoreTypeMax; StoreType++) {
+        if (VariableStoreList[StoreType] != NULL) {
           break;
         }
       }
@@ -568,12 +582,12 @@ VariableServiceGetNextVariableInternal (
       // 1. current storage is the last one, or
       // 2. no further storage
       //
-      if (Type == VariableStoreTypeMax) {
+      if (StoreType == VariableStoreTypeMax) {
         Status = EFI_NOT_FOUND;
         goto Done;
       }
-      Variable.StartPtr = GetStartPointer (VariableStoreHeader[Type]);
-      Variable.EndPtr   = GetEndPointer   (VariableStoreHeader[Type]);
+      Variable.StartPtr = GetStartPointer (VariableStoreList[StoreType]);
+      Variable.EndPtr   = GetEndPointer   (VariableStoreList[StoreType]);
       Variable.CurrPtr  = Variable.StartPtr;
     }
 
@@ -605,11 +619,11 @@ VariableServiceGetNextVariableInternal (
         //
         // Don't return NV variable when HOB overrides it
         //
-        if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) &&
-            (Variable.StartPtr == GetStartPointer (VariableStoreHeader[VariableStoreTypeNv]))
+        if ((VariableStoreList[VariableStoreTypeHob] != NULL) && (VariableStoreList[VariableStoreTypeNv] != NULL) &&
+            (Variable.StartPtr == GetStartPointer (VariableStoreList[VariableStoreTypeNv]))
            ) {
-          VariableInHob.StartPtr = GetStartPointer (VariableStoreHeader[VariableStoreTypeHob]);
-          VariableInHob.EndPtr   = GetEndPointer   (VariableStoreHeader[VariableStoreTypeHob]);
+          VariableInHob.StartPtr = GetStartPointer (VariableStoreList[VariableStoreTypeHob]);
+          VariableInHob.EndPtr   = GetEndPointer   (VariableStoreList[VariableStoreTypeHob]);
           Status = FindVariableEx (
                      GetVariableNamePtr (Variable.CurrPtr),
                      GetVendorGuidPtr (Variable.CurrPtr),
-- 
2.16.2.windows.1


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [PATCH V7 03/10] MdeModulePkg/Variable: Parameterize VARIABLE_INFO_ENTRY buffer
  2019-11-01 17:34 [PATCH V7 00/10] UEFI Variable SMI Reduction Kubacki, Michael A
  2019-11-01 17:34 ` [PATCH V7 01/10] MdeModulePkg/Variable: Consolidate common parsing functions Kubacki, Michael A
  2019-11-01 17:34 ` [PATCH V7 02/10] MdeModulePkg/Variable: Parameterize GetNextVariableInternal () stores Kubacki, Michael A
@ 2019-11-01 17:34 ` Kubacki, Michael A
  2019-11-01 17:34 ` [PATCH V7 04/10] MdeModulePkg/Variable: Parameterize auth status in VariableParsing Kubacki, Michael A
                   ` (7 subsequent siblings)
  10 siblings, 0 replies; 14+ messages in thread
From: Kubacki, Michael A @ 2019-11-01 17:34 UTC (permalink / raw)
  To: devel
  Cc: Dandan Bi, Ard Biesheuvel, Eric Dong, Laszlo Ersek, Liming Gao,
	Michael D Kinney, Ray Ni, Jian J Wang, Hao A Wu, Jiewen Yao

UpdateVariableInfo () currently accepts parameters regarding updates
to be made to a global variable of type VARIABLE_INFO_ENTRY. This
change passes the structure by pointer to UpdateVariableInfo ()
so structures other than the fixed global variable can be updated.

Cc: Dandan Bi <dandan.bi@intel.com>
Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Eric Dong <eric.dong@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Cc: Liming Gao <liming.gao@intel.com>
Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Hao A Wu <hao.a.wu@intel.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Signed-off-by: Michael Kubacki <michael.a.kubacki@intel.com>
---
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h | 18 +++++----
 MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c        | 14 +++----
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c | 41 +++++++++++---------
 3 files changed, 39 insertions(+), 34 deletions(-)

diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h
index 6555316f52..1777ce0e69 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h
@@ -286,13 +286,14 @@ VariableServiceGetNextVariableInternal (
   the transaction. Data is allocated by this routine, but never
   freed.
 
-  @param[in] VariableName   Name of the Variable to track.
-  @param[in] VendorGuid     Guid of the Variable to track.
-  @param[in] Volatile       TRUE if volatile FALSE if non-volatile.
-  @param[in] Read           TRUE if GetVariable() was called.
-  @param[in] Write          TRUE if SetVariable() was called.
-  @param[in] Delete         TRUE if deleted via SetVariable().
-  @param[in] Cache          TRUE for a cache hit.
+  @param[in]      VariableName   Name of the Variable to track.
+  @param[in]      VendorGuid     Guid of the Variable to track.
+  @param[in]      Volatile       TRUE if volatile FALSE if non-volatile.
+  @param[in]      Read           TRUE if GetVariable() was called.
+  @param[in]      Write          TRUE if SetVariable() was called.
+  @param[in]      Delete         TRUE if deleted via SetVariable().
+  @param[in]      Cache          TRUE for a cache hit.
+  @param[in,out]  VariableInfo   Pointer to a pointer of VARIABLE_INFO_ENTRY structures.
 
 **/
 VOID
@@ -303,7 +304,8 @@ UpdateVariableInfo (
   IN  BOOLEAN                 Read,
   IN  BOOLEAN                 Write,
   IN  BOOLEAN                 Delete,
-  IN  BOOLEAN                 Cache
+  IN  BOOLEAN                 Cache,
+  IN OUT VARIABLE_INFO_ENTRY  **VariableInfo
   );
 
 #endif
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
index 70af86db24..5cc12c2ae0 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
@@ -1641,7 +1641,7 @@ UpdateVariable (
         // go to delete this variable in variable HOB and
         // try to flush other variables from HOB to flash.
         //
-        UpdateVariableInfo (VariableName, VendorGuid, FALSE, FALSE, FALSE, TRUE, FALSE);
+        UpdateVariableInfo (VariableName, VendorGuid, FALSE, FALSE, FALSE, TRUE, FALSE, &gVariableInfo);
         FlushHobVariableToFlash (VariableName, VendorGuid);
         return EFI_SUCCESS;
       }
@@ -1758,7 +1758,7 @@ UpdateVariable (
                  &State
                  );
       if (!EFI_ERROR (Status)) {
-        UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, FALSE, TRUE, FALSE);
+        UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, FALSE, TRUE, FALSE, &gVariableInfo);
         if (!Variable->Volatile) {
           CacheVariable->CurrPtr->State = State;
           FlushHobVariableToFlash (VariableName, VendorGuid);
@@ -1777,7 +1777,7 @@ UpdateVariable (
       //
       // Variable content unchanged and no need to update timestamp, just return.
       //
-      UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE);
+      UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE, &gVariableInfo);
       Status = EFI_SUCCESS;
       goto Done;
     } else if ((CacheVariable->CurrPtr->State == VAR_ADDED) ||
@@ -2006,7 +2006,7 @@ UpdateVariable (
           CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));
           CacheVariable->InDeletedTransitionPtr = NULL;
         }
-        UpdateVariableInfo (VariableName, VendorGuid, FALSE, FALSE, TRUE, FALSE, FALSE);
+        UpdateVariableInfo (VariableName, VendorGuid, FALSE, FALSE, TRUE, FALSE, FALSE, &gVariableInfo);
         FlushHobVariableToFlash (VariableName, VendorGuid);
       } else {
         if (IsCommonUserVariable && ((VarSize + mVariableModuleGlobal->CommonUserVariableTotalSize) > mVariableModuleGlobal->CommonMaxUserVariableSpace)) {
@@ -2156,7 +2156,7 @@ UpdateVariable (
           CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));
           CacheVariable->InDeletedTransitionPtr = NULL;
         }
-        UpdateVariableInfo (VariableName, VendorGuid, TRUE, FALSE, TRUE, FALSE, FALSE);
+        UpdateVariableInfo (VariableName, VendorGuid, TRUE, FALSE, TRUE, FALSE, FALSE, &gVariableInfo);
       }
       goto Done;
     }
@@ -2227,7 +2227,7 @@ UpdateVariable (
   }
 
   if (!EFI_ERROR (Status)) {
-    UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE);
+    UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE, &gVariableInfo);
     if (!Volatile) {
       FlushHobVariableToFlash (VariableName, VendorGuid);
     }
@@ -2306,7 +2306,7 @@ VariableServiceGetVariable (
     }
 
     *DataSize = VarDataSize;
-    UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE);
+    UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE, &gVariableInfo);
 
     Status = EFI_SUCCESS;
     goto Done;
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c
index d6bb916e68..870c9e3742 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c
@@ -660,13 +660,14 @@ Done:
   the transaction. Data is allocated by this routine, but never
   freed.
 
-  @param[in] VariableName   Name of the Variable to track.
-  @param[in] VendorGuid     Guid of the Variable to track.
-  @param[in] Volatile       TRUE if volatile FALSE if non-volatile.
-  @param[in] Read           TRUE if GetVariable() was called.
-  @param[in] Write          TRUE if SetVariable() was called.
-  @param[in] Delete         TRUE if deleted via SetVariable().
-  @param[in] Cache          TRUE for a cache hit.
+  @param[in]      VariableName   Name of the Variable to track.
+  @param[in]      VendorGuid     Guid of the Variable to track.
+  @param[in]      Volatile       TRUE if volatile FALSE if non-volatile.
+  @param[in]      Read           TRUE if GetVariable() was called.
+  @param[in]      Write          TRUE if SetVariable() was called.
+  @param[in]      Delete         TRUE if deleted via SetVariable().
+  @param[in]      Cache          TRUE for a cache hit.
+  @param[in,out]  VariableInfo   Pointer to a pointer of VARIABLE_INFO_ENTRY structures.
 
 **/
 VOID
@@ -677,35 +678,38 @@ UpdateVariableInfo (
   IN  BOOLEAN                 Read,
   IN  BOOLEAN                 Write,
   IN  BOOLEAN                 Delete,
-  IN  BOOLEAN                 Cache
+  IN  BOOLEAN                 Cache,
+  IN OUT VARIABLE_INFO_ENTRY  **VariableInfo
   )
 {
   VARIABLE_INFO_ENTRY   *Entry;
 
   if (FeaturePcdGet (PcdVariableCollectStatistics)) {
-
+    if (VariableName == NULL || VendorGuid == NULL || VariableInfo == NULL) {
+      return;
+    }
     if (AtRuntime ()) {
       // Don't collect statistics at runtime.
       return;
     }
 
-    if (gVariableInfo == NULL) {
+    if (*VariableInfo == NULL) {
       //
       // On the first call allocate a entry and place a pointer to it in
       // the EFI System Table.
       //
-      gVariableInfo = AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY));
-      ASSERT (gVariableInfo != NULL);
+      *VariableInfo = AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY));
+      ASSERT (*VariableInfo != NULL);
 
-      CopyGuid (&gVariableInfo->VendorGuid, VendorGuid);
-      gVariableInfo->Name = AllocateZeroPool (StrSize (VariableName));
-      ASSERT (gVariableInfo->Name != NULL);
-      StrCpyS (gVariableInfo->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName);
-      gVariableInfo->Volatile = Volatile;
+      CopyGuid (&(*VariableInfo)->VendorGuid, VendorGuid);
+      (*VariableInfo)->Name = AllocateZeroPool (StrSize (VariableName));
+      ASSERT ((*VariableInfo)->Name != NULL);
+      StrCpyS ((*VariableInfo)->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName);
+      (*VariableInfo)->Volatile = Volatile;
     }
 
 
-    for (Entry = gVariableInfo; Entry != NULL; Entry = Entry->Next) {
+    for (Entry = (*VariableInfo); Entry != NULL; Entry = Entry->Next) {
       if (CompareGuid (VendorGuid, &Entry->VendorGuid)) {
         if (StrCmp (VariableName, Entry->Name) == 0) {
           if (Read) {
@@ -739,7 +743,6 @@ UpdateVariableInfo (
         StrCpyS (Entry->Next->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName);
         Entry->Next->Volatile = Volatile;
       }
-
     }
   }
 }
-- 
2.16.2.windows.1


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [PATCH V7 04/10] MdeModulePkg/Variable: Parameterize auth status in VariableParsing
  2019-11-01 17:34 [PATCH V7 00/10] UEFI Variable SMI Reduction Kubacki, Michael A
                   ` (2 preceding siblings ...)
  2019-11-01 17:34 ` [PATCH V7 03/10] MdeModulePkg/Variable: Parameterize VARIABLE_INFO_ENTRY buffer Kubacki, Michael A
@ 2019-11-01 17:34 ` Kubacki, Michael A
  2019-11-01 17:34 ` [PATCH V7 05/10] MdeModulePkg/Variable: Add a file for NV variable functions Kubacki, Michael A
                   ` (6 subsequent siblings)
  10 siblings, 0 replies; 14+ messages in thread
From: Kubacki, Michael A @ 2019-11-01 17:34 UTC (permalink / raw)
  To: devel
  Cc: Dandan Bi, Ard Biesheuvel, Eric Dong, Laszlo Ersek, Liming Gao,
	Michael D Kinney, Ray Ni, Jian J Wang, Hao A Wu, Jiewen Yao

The file VariableParsing.c provides generic functionality related
to parsing variable related structures and information. In order to
calculate offsets for certain operations, the functions must know if
authenticated variables are enabled as this increases the size of
variable headers.

This change removes linking against a global variable in an external file
in favor of passing the authenticated variable status as a parameter to
the variable parsing functions.

Cc: Dandan Bi <dandan.bi@intel.com>
Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Eric Dong <eric.dong@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Cc: Liming Gao <liming.gao@intel.com>
Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Hao A Wu <hao.a.wu@intel.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Signed-off-by: Michael Kubacki <michael.a.kubacki@intel.com>
---
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h |  82 +++++--
 MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c        | 258 ++++++++++++++------
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c   |  15 +-
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c | 146 +++++++----
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c     |   5 +-
 5 files changed, 339 insertions(+), 167 deletions(-)

diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h
index 1777ce0e69..92a729d140 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h
@@ -49,53 +49,65 @@ GetVariableStoreStatus (
 /**
   This code gets the size of variable header.
 
+  @param[in]  AuthFormat    TRUE indicates authenticated variables are used.
+                            FALSE indicates authenticated variables are not used.
+
   @return Size of variable header in bytes in type UINTN.
 
 **/
 UINTN
 GetVariableHeaderSize (
-  VOID
+  IN  BOOLEAN   AuthFormat
   );
 
 /**
 
   This code gets the size of name of variable.
 
-  @param Variable        Pointer to the Variable Header.
+  @param[in]  Variable      Pointer to the variable header.
+  @param[in]  AuthFormat    TRUE indicates authenticated variables are used.
+                            FALSE indicates authenticated variables are not used.
 
   @return UINTN          Size of variable in bytes.
 
 **/
 UINTN
 NameSizeOfVariable (
-  IN  VARIABLE_HEADER   *Variable
+  IN  VARIABLE_HEADER   *Variable,
+  IN  BOOLEAN           AuthFormat
   );
 
 /**
   This code sets the size of name of variable.
 
-  @param[in] Variable   Pointer to the Variable Header.
-  @param[in] NameSize   Name size to set.
+  @param[in]  Variable      Pointer to the Variable Header.
+  @param[in]  NameSize      Name size to set.
+  @param[in]  AuthFormat    TRUE indicates authenticated variables are used.
+                            FALSE indicates authenticated variables are not used.
 
 **/
 VOID
 SetNameSizeOfVariable (
   IN VARIABLE_HEADER    *Variable,
-  IN UINTN              NameSize
+  IN UINTN              NameSize,
+  IN BOOLEAN            AuthFormat
   );
 
 /**
 
   This code gets the size of variable data.
 
-  @param Variable        Pointer to the Variable Header.
+  @param[in]  Variable      Pointer to the Variable Header.
+  @param[in]  AuthFormat    TRUE indicates authenticated variables are used.
+                            FALSE indicates authenticated variables are not used.
 
   @return Size of variable in bytes.
 
 **/
 UINTN
 DataSizeOfVariable (
-  IN  VARIABLE_HEADER   *Variable
+  IN  VARIABLE_HEADER   *Variable,
+  IN  BOOLEAN           AuthFormat
   );
 
 /**
@@ -103,80 +115,98 @@ DataSizeOfVariable (
 
   @param[in] Variable   Pointer to the Variable Header.
   @param[in] DataSize   Data size to set.
+  @param[in] AuthFormat TRUE indicates authenticated variables are used.
+                        FALSE indicates authenticated variables are not used.
 
 **/
 VOID
 SetDataSizeOfVariable (
-  IN VARIABLE_HEADER    *Variable,
-  IN UINTN              DataSize
+  IN  VARIABLE_HEADER   *Variable,
+  IN  UINTN             DataSize,
+  IN  BOOLEAN           AuthFormat
   );
 
 /**
 
   This code gets the pointer to the variable name.
 
-  @param Variable        Pointer to the Variable Header.
+  @param[in] Variable     Pointer to the Variable Header.
+  @param[in] AuthFormat   TRUE indicates authenticated variables are used.
+                          FALSE indicates authenticated variables are not used.
 
   @return Pointer to Variable Name which is Unicode encoding.
 
 **/
 CHAR16 *
 GetVariableNamePtr (
-  IN  VARIABLE_HEADER   *Variable
+  IN  VARIABLE_HEADER   *Variable,
+  IN  BOOLEAN           AuthFormat
   );
 
 /**
   This code gets the pointer to the variable guid.
 
-  @param Variable   Pointer to the Variable Header.
+  @param[in] Variable     Pointer to the Variable Header.
+  @param[in] AuthFormat   TRUE indicates authenticated variables are used.
+                          FALSE indicates authenticated variables are not used.
 
   @return A EFI_GUID* pointer to Vendor Guid.
 
 **/
 EFI_GUID *
 GetVendorGuidPtr (
-  IN VARIABLE_HEADER    *Variable
+  IN  VARIABLE_HEADER    *Variable,
+  IN  BOOLEAN            AuthFormat
   );
 
 /**
 
   This code gets the pointer to the variable data.
 
-  @param Variable        Pointer to the Variable Header.
+  @param[in] Variable     Pointer to the Variable Header.
+  @param[in] AuthFormat   TRUE indicates authenticated variables are used.
+                          FALSE indicates authenticated variables are not used.
 
   @return Pointer to Variable Data.
 
 **/
 UINT8 *
 GetVariableDataPtr (
-  IN  VARIABLE_HEADER   *Variable
+  IN  VARIABLE_HEADER    *Variable,
+  IN  BOOLEAN            AuthFormat
   );
 
 /**
   This code gets the variable data offset related to variable header.
 
-  @param Variable        Pointer to the Variable Header.
+  @param[in] Variable     Pointer to the Variable Header.
+  @param[in] AuthFormat   TRUE indicates authenticated variables are used.
+                          FALSE indicates authenticated variables are not used.
 
   @return Variable Data offset.
 
 **/
 UINTN
 GetVariableDataOffset (
-  IN  VARIABLE_HEADER   *Variable
+  IN  VARIABLE_HEADER   *Variable,
+  IN  BOOLEAN           AuthFormat
   );
 
 /**
 
   This code gets the pointer to the next variable header.
 
-  @param Variable        Pointer to the Variable Header.
+  @param[in] Variable     Pointer to the Variable Header.
+  @param[in] AuthFormat   TRUE indicates authenticated variables are used.
+                          FALSE indicates authenticated variables are not used.
 
   @return Pointer to next variable header.
 
 **/
 VARIABLE_HEADER *
 GetNextVariablePtr (
-  IN  VARIABLE_HEADER   *Variable
+  IN  VARIABLE_HEADER   *Variable,
+  IN  BOOLEAN           AuthFormat
   );
 
 /**
@@ -235,6 +265,8 @@ VariableCompareTimeStampInternal (
   @param[in]       IgnoreRtCheck       Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute
                                        check at runtime when searching variable.
   @param[in, out]  PtrTrack            Variable Track Pointer structure that contains Variable Information.
+  @param[in]       AuthFormat          TRUE indicates authenticated variables are used.
+                                       FALSE indicates authenticated variables are not used.
 
   @retval          EFI_SUCCESS         Variable found successfully
   @retval          EFI_NOT_FOUND       Variable not found
@@ -244,7 +276,8 @@ FindVariableEx (
   IN     CHAR16                  *VariableName,
   IN     EFI_GUID                *VendorGuid,
   IN     BOOLEAN                 IgnoreRtCheck,
-  IN OUT VARIABLE_POINTER_TRACK  *PtrTrack
+  IN OUT VARIABLE_POINTER_TRACK  *PtrTrack,
+  IN     BOOLEAN                 AuthFormat
   );
 
 /**
@@ -258,10 +291,12 @@ FindVariableEx (
   @param[in]  VariableStoreList A list of variable stores that should be used to get the next variable.
                                 The maximum number of entries is the max value of VARIABLE_STORE_TYPE.
   @param[out] VariablePtr       Pointer to variable header address.
+  @param[in]  AuthFormat        TRUE indicates authenticated variables are used.
+                                FALSE indicates authenticated variables are not used.
 
   @retval EFI_SUCCESS           The function completed successfully.
   @retval EFI_NOT_FOUND         The next variable was not found.
-  @retval EFI_INVALID_PARAMETER If VariableName is nt an empty string, while VendorGuid is NULL.
+  @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while VendorGuid is NULL.
   @retval EFI_INVALID_PARAMETER The input values of VariableName and VendorGuid are not a name and
                                 GUID of an existing variable.
 
@@ -272,7 +307,8 @@ VariableServiceGetNextVariableInternal (
   IN  CHAR16                *VariableName,
   IN  EFI_GUID              *VendorGuid,
   IN  VARIABLE_STORE_HEADER **VariableStoreList,
-  OUT VARIABLE_HEADER       **VariablePtr
+  OUT VARIABLE_HEADER       **VariablePtr,
+  IN  BOOLEAN               AuthFormat
   );
 
 /**
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
index 5cc12c2ae0..2e32905dfe 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
@@ -311,7 +311,7 @@ RecordVarErrorFlag (
              FALSE
              );
   if (!EFI_ERROR (Status)) {
-    VarErrFlag = (VAR_ERROR_FLAG *) GetVariableDataPtr (Variable.CurrPtr);
+    VarErrFlag = (VAR_ERROR_FLAG *) GetVariableDataPtr (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
     TempFlag = *VarErrFlag;
     TempFlag &= Flag;
     if (TempFlag == *VarErrFlag) {
@@ -369,7 +369,7 @@ InitializeVarErrorFlag (
              FALSE
              );
   if (!EFI_ERROR (Status)) {
-    VarErrFlag = *((VAR_ERROR_FLAG *) GetVariableDataPtr (Variable.CurrPtr));
+    VarErrFlag = *((VAR_ERROR_FLAG *) GetVariableDataPtr (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat));
     if (VarErrFlag == Flag) {
       return;
     }
@@ -410,7 +410,11 @@ IsUserVariable (
   // then no need to check if the variable is user variable or not specially.
   //
   if (mEndOfDxe && (mVariableModuleGlobal->CommonMaxUserVariableSpace != mVariableModuleGlobal->CommonVariableSpace)) {
-    if (VarCheckLibVariablePropertyGet (GetVariableNamePtr (Variable), GetVendorGuidPtr (Variable), &Property) == EFI_NOT_FOUND) {
+    if (VarCheckLibVariablePropertyGet (
+          GetVariableNamePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat),
+          GetVendorGuidPtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat),
+          &Property
+          ) == EFI_NOT_FOUND) {
       return TRUE;
     }
   }
@@ -439,10 +443,14 @@ CalculateCommonUserVariableTotalSize (
   if (mEndOfDxe && (mVariableModuleGlobal->CommonMaxUserVariableSpace != mVariableModuleGlobal->CommonVariableSpace)) {
     Variable = GetStartPointer (mNvVariableCache);
     while (IsValidVariableHeader (Variable, GetEndPointer (mNvVariableCache))) {
-      NextVariable = GetNextVariablePtr (Variable);
+      NextVariable = GetNextVariablePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat);
       VariableSize = (UINTN) NextVariable - (UINTN) Variable;
       if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
-        if (VarCheckLibVariablePropertyGet (GetVariableNamePtr (Variable), GetVendorGuidPtr (Variable), &Property) == EFI_NOT_FOUND) {
+        if (VarCheckLibVariablePropertyGet (
+              GetVariableNamePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat),
+              GetVendorGuidPtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat),
+              &Property
+              ) == EFI_NOT_FOUND) {
           //
           // No property, it is user variable.
           //
@@ -518,7 +526,9 @@ Reclaim (
   UINTN                 HwErrVariableTotalSize;
   VARIABLE_HEADER       *UpdatingVariable;
   VARIABLE_HEADER       *UpdatingInDeletedTransition;
+  BOOLEAN               AuthFormat;
 
+  AuthFormat = mVariableModuleGlobal->VariableGlobal.AuthFormat;
   UpdatingVariable = NULL;
   UpdatingInDeletedTransition = NULL;
   if (UpdatingPtrTrack != NULL) {
@@ -540,7 +550,7 @@ Reclaim (
     MaximumBufferSize = sizeof (VARIABLE_STORE_HEADER);
 
     while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {
-      NextVariable = GetNextVariablePtr (Variable);
+      NextVariable = GetNextVariablePtr (Variable, AuthFormat);
       if ((Variable->State == VAR_ADDED || Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) &&
           Variable != UpdatingVariable &&
           Variable != UpdatingInDeletedTransition
@@ -590,7 +600,7 @@ Reclaim (
   //
   Variable = GetStartPointer (VariableStoreHeader);
   while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {
-    NextVariable = GetNextVariablePtr (Variable);
+    NextVariable = GetNextVariablePtr (Variable, AuthFormat);
     if (Variable != UpdatingVariable && Variable->State == VAR_ADDED) {
       VariableSize = (UINTN) NextVariable - (UINTN) Variable;
       CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize);
@@ -612,7 +622,7 @@ Reclaim (
   //
   Variable = GetStartPointer (VariableStoreHeader);
   while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {
-    NextVariable = GetNextVariablePtr (Variable);
+    NextVariable = GetNextVariablePtr (Variable, AuthFormat);
     if (Variable != UpdatingVariable && Variable != UpdatingInDeletedTransition && Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
 
       //
@@ -624,13 +634,14 @@ Reclaim (
       FoundAdded = FALSE;
       AddedVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer);
       while (IsValidVariableHeader (AddedVariable, GetEndPointer ((VARIABLE_STORE_HEADER *) ValidBuffer))) {
-        NextAddedVariable = GetNextVariablePtr (AddedVariable);
-        NameSize = NameSizeOfVariable (AddedVariable);
-        if (CompareGuid (GetVendorGuidPtr (AddedVariable), GetVendorGuidPtr (Variable)) &&
-            NameSize == NameSizeOfVariable (Variable)
-           ) {
-          Point0 = (VOID *) GetVariableNamePtr (AddedVariable);
-          Point1 = (VOID *) GetVariableNamePtr (Variable);
+        NextAddedVariable = GetNextVariablePtr (AddedVariable, AuthFormat);
+        NameSize = NameSizeOfVariable (AddedVariable, AuthFormat);
+        if (CompareGuid (
+              GetVendorGuidPtr (AddedVariable, AuthFormat),
+              GetVendorGuidPtr (Variable, AuthFormat)
+            ) && NameSize == NameSizeOfVariable (Variable, AuthFormat)) {
+          Point0 = (VOID *) GetVariableNamePtr (AddedVariable, AuthFormat);
+          Point1 = (VOID *) GetVariableNamePtr (Variable, AuthFormat);
           if (CompareMem (Point0, Point1, NameSize) == 0) {
             FoundAdded = TRUE;
             break;
@@ -735,7 +746,7 @@ Reclaim (
       mVariableModuleGlobal->CommonUserVariableTotalSize = 0;
       Variable = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableBase);
       while (IsValidVariableHeader (Variable, GetEndPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableBase))) {
-        NextVariable = GetNextVariablePtr (Variable);
+        NextVariable = GetNextVariablePtr (Variable, AuthFormat);
         VariableSize = (UINTN) NextVariable - (UINTN) Variable;
         if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
           mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize;
@@ -829,7 +840,13 @@ FindVariable (
     PtrTrack->EndPtr   = GetEndPointer   (VariableStoreHeader[Type]);
     PtrTrack->Volatile = (BOOLEAN) (Type == VariableStoreTypeVolatile);
 
-    Status = FindVariableEx (VariableName, VendorGuid, IgnoreRtCheck, PtrTrack);
+    Status =  FindVariableEx (
+                VariableName,
+                VendorGuid,
+                IgnoreRtCheck,
+                PtrTrack,
+                mVariableModuleGlobal->VariableGlobal.AuthFormat
+                );
     if (!EFI_ERROR (Status)) {
       return Status;
     }
@@ -1199,7 +1216,11 @@ CheckRemainingSpaceForConsistencyInternal (
     VarNameSize += GET_PAD_SIZE (VarNameSize);
     VarDataSize  = VariableEntry->VariableSize;
     VarDataSize += GET_PAD_SIZE (VarDataSize);
-    VariableEntry->VariableSize = HEADER_ALIGN (GetVariableHeaderSize () + VarNameSize + VarDataSize);
+    VariableEntry->VariableSize = HEADER_ALIGN (
+                                    GetVariableHeaderSize (
+                                      mVariableModuleGlobal->VariableGlobal.AuthFormat
+                                      ) + VarNameSize + VarDataSize
+                                    );
 
     TotalNeededSize += VariableEntry->VariableSize;
     VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *);
@@ -1232,13 +1253,14 @@ CheckRemainingSpaceForConsistencyInternal (
                VariableEntry->Name,
                VariableEntry->Guid,
                FALSE,
-               &VariablePtrTrack
+               &VariablePtrTrack,
+               mVariableModuleGlobal->VariableGlobal.AuthFormat
                );
     if (!EFI_ERROR (Status)) {
       //
       // Get size of Variable[Index].
       //
-      NextVariable = GetNextVariablePtr (VariablePtrTrack.CurrPtr);
+      NextVariable = GetNextVariablePtr (VariablePtrTrack.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
       OriginalVarSize = (UINTN) NextVariable - (UINTN) VariablePtrTrack.CurrPtr;
       //
       // Add the original size of Variable[Index] to remaining variable storage size.
@@ -1410,8 +1432,8 @@ AutoUpdateLangVariable (
       // Update Lang
       //
       VariableName = EFI_PLATFORM_LANG_VARIABLE_NAME;
-      Data         = GetVariableDataPtr (Variable.CurrPtr);
-      DataSize     = DataSizeOfVariable (Variable.CurrPtr);
+      Data         = GetVariableDataPtr (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
+      DataSize     = DataSizeOfVariable (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
     } else {
       Status = FindVariable (EFI_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
       if (!EFI_ERROR (Status)) {
@@ -1419,8 +1441,8 @@ AutoUpdateLangVariable (
         // Update PlatformLang
         //
         VariableName = EFI_LANG_VARIABLE_NAME;
-        Data         = GetVariableDataPtr (Variable.CurrPtr);
-        DataSize     = DataSizeOfVariable (Variable.CurrPtr);
+        Data         = GetVariableDataPtr (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
+        DataSize     = DataSizeOfVariable (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
       } else {
         //
         // Neither PlatformLang nor Lang is set, directly return
@@ -1598,6 +1620,7 @@ UpdateVariable (
   BOOLEAN                             IsCommonVariable;
   BOOLEAN                             IsCommonUserVariable;
   AUTHENTICATED_VARIABLE_HEADER       *AuthVariable;
+  BOOLEAN                             AuthFormat;
 
   if (mVariableModuleGlobal->FvbInstance == NULL && !mVariableModuleGlobal->VariableGlobal.EmuNvMode) {
     //
@@ -1619,6 +1642,8 @@ UpdateVariable (
     }
   }
 
+  AuthFormat = mVariableModuleGlobal->VariableGlobal.AuthFormat;
+
   //
   // Check if CacheVariable points to the variable in variable HOB.
   // If yes, let CacheVariable points to the variable in NV variable cache.
@@ -1630,7 +1655,7 @@ UpdateVariable (
     CacheVariable->StartPtr = GetStartPointer (mNvVariableCache);
     CacheVariable->EndPtr   = GetEndPointer   (mNvVariableCache);
     CacheVariable->Volatile = FALSE;
-    Status = FindVariableEx (VariableName, VendorGuid, FALSE, CacheVariable);
+    Status = FindVariableEx (VariableName, VendorGuid, FALSE, CacheVariable, AuthFormat);
     if (CacheVariable->CurrPtr == NULL || EFI_ERROR (Status)) {
       //
       // There is no matched variable in NV variable cache.
@@ -1770,8 +1795,8 @@ UpdateVariable (
     // If the variable is marked valid, and the same data has been passed in,
     // then return to the caller immediately.
     //
-    if (DataSizeOfVariable (CacheVariable->CurrPtr) == DataSize &&
-        (CompareMem (Data, GetVariableDataPtr (CacheVariable->CurrPtr), DataSize) == 0) &&
+    if (DataSizeOfVariable (CacheVariable->CurrPtr, AuthFormat) == DataSize &&
+        (CompareMem (Data, GetVariableDataPtr (CacheVariable->CurrPtr, AuthFormat), DataSize) == 0) &&
         ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) &&
         (TimeStamp == NULL)) {
       //
@@ -1791,9 +1816,13 @@ UpdateVariable (
         // NOTE: From 0 to DataOffset of NextVariable is reserved for Variable Header and Name.
         // From DataOffset of NextVariable is to save the existing variable data.
         //
-        DataOffset = GetVariableDataOffset (CacheVariable->CurrPtr);
+        DataOffset = GetVariableDataOffset (CacheVariable->CurrPtr, AuthFormat);
         BufferForMerge = (UINT8 *) ((UINTN) NextVariable + DataOffset);
-        CopyMem (BufferForMerge, (UINT8 *) ((UINTN) CacheVariable->CurrPtr + DataOffset), DataSizeOfVariable (CacheVariable->CurrPtr));
+        CopyMem (
+          BufferForMerge,
+          (UINT8 *) ((UINTN) CacheVariable->CurrPtr + DataOffset),
+          DataSizeOfVariable (CacheVariable->CurrPtr, AuthFormat)
+          );
 
         //
         // Set Max Auth/Non-Volatile/Volatile Variable Data Size as default MaxDataSize.
@@ -1814,15 +1843,22 @@ UpdateVariable (
           MaxDataSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - DataOffset;
         }
 
-        if (DataSizeOfVariable (CacheVariable->CurrPtr) + DataSize > MaxDataSize) {
+        if (DataSizeOfVariable (CacheVariable->CurrPtr, AuthFormat) + DataSize > MaxDataSize) {
           //
           // Existing data size + new data size exceed maximum variable size limitation.
           //
           Status = EFI_INVALID_PARAMETER;
           goto Done;
         }
-        CopyMem ((UINT8*) ((UINTN) BufferForMerge + DataSizeOfVariable (CacheVariable->CurrPtr)), Data, DataSize);
-        MergedBufSize = DataSizeOfVariable (CacheVariable->CurrPtr) + DataSize;
+        CopyMem (
+          (UINT8*) (
+            (UINTN) BufferForMerge + DataSizeOfVariable (CacheVariable->CurrPtr, AuthFormat)
+            ),
+          Data,
+          DataSize
+          );
+        MergedBufSize = DataSizeOfVariable (CacheVariable->CurrPtr, AuthFormat) +
+                          DataSize;
 
         //
         // BufferForMerge(from DataOffset of NextVariable) has included the merged existing and new data.
@@ -1925,7 +1961,7 @@ UpdateVariable (
   //
   NextVariable->Attributes  = Attributes & (~EFI_VARIABLE_APPEND_WRITE);
 
-  VarNameOffset                 = GetVariableHeaderSize ();
+  VarNameOffset                 = GetVariableHeaderSize (AuthFormat);
   VarNameSize                   = StrSize (VariableName);
   CopyMem (
     (UINT8 *) ((UINTN) NextVariable + VarNameOffset),
@@ -1946,14 +1982,18 @@ UpdateVariable (
       );
   }
 
-  CopyMem (GetVendorGuidPtr (NextVariable), VendorGuid, sizeof (EFI_GUID));
+  CopyMem (
+    GetVendorGuidPtr (NextVariable, AuthFormat),
+    VendorGuid,
+    sizeof (EFI_GUID)
+    );
   //
   // There will be pad bytes after Data, the NextVariable->NameSize and
   // NextVariable->DataSize should not include pad size so that variable
   // service can get actual size in GetVariable.
   //
-  SetNameSizeOfVariable (NextVariable, VarNameSize);
-  SetDataSizeOfVariable (NextVariable, DataSize);
+  SetNameSizeOfVariable (NextVariable, VarNameSize, AuthFormat);
+  SetDataSizeOfVariable (NextVariable, DataSize, AuthFormat);
 
   //
   // The actual size of the variable that stores in storage should
@@ -2036,7 +2076,7 @@ UpdateVariable (
                  TRUE,
                  Fvb,
                  mVariableModuleGlobal->NonVolatileLastVariableOffset,
-                 (UINT32) GetVariableHeaderSize (),
+                 (UINT32) GetVariableHeaderSize (AuthFormat),
                  (UINT8 *) NextVariable
                  );
 
@@ -2069,9 +2109,9 @@ UpdateVariable (
                  FALSE,
                  TRUE,
                  Fvb,
-                 mVariableModuleGlobal->NonVolatileLastVariableOffset + GetVariableHeaderSize (),
-                 (UINT32) (VarSize - GetVariableHeaderSize ()),
-                 (UINT8 *) NextVariable + GetVariableHeaderSize ()
+                 mVariableModuleGlobal->NonVolatileLastVariableOffset + GetVariableHeaderSize (AuthFormat),
+                 (UINT32) (VarSize - GetVariableHeaderSize (AuthFormat)),
+                 (UINT8 *) NextVariable + GetVariableHeaderSize (AuthFormat)
                  );
 
       if (EFI_ERROR (Status)) {
@@ -2291,7 +2331,7 @@ VariableServiceGetVariable (
   //
   // Get data size
   //
-  VarDataSize = DataSizeOfVariable (Variable.CurrPtr);
+  VarDataSize = DataSizeOfVariable (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
   ASSERT (VarDataSize != 0);
 
   if (*DataSize >= VarDataSize) {
@@ -2300,7 +2340,7 @@ VariableServiceGetVariable (
       goto Done;
     }
 
-    CopyMem (Data, GetVariableDataPtr (Variable.CurrPtr), VarDataSize);
+    CopyMem (Data, GetVariableDataPtr (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat), VarDataSize);
     if (Attributes != NULL) {
       *Attributes = Variable.CurrPtr->Attributes;
     }
@@ -2357,6 +2397,7 @@ VariableServiceGetNextVariableName (
   EFI_STATUS              Status;
   UINTN                   MaxLen;
   UINTN                   VarNameSize;
+  BOOLEAN                 AuthFormat;
   VARIABLE_HEADER         *VariablePtr;
   VARIABLE_STORE_HEADER   *VariableStoreHeader[VariableStoreTypeMax];
 
@@ -2364,6 +2405,8 @@ VariableServiceGetNextVariableName (
     return EFI_INVALID_PARAMETER;
   }
 
+  AuthFormat = mVariableModuleGlobal->VariableGlobal.AuthFormat;
+
   //
   // Calculate the possible maximum length of name string, including the Null terminator.
   //
@@ -2387,13 +2430,27 @@ VariableServiceGetNextVariableName (
   VariableStoreHeader[VariableStoreTypeHob]      = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
   VariableStoreHeader[VariableStoreTypeNv]       = mNvVariableCache;
 
-  Status = VariableServiceGetNextVariableInternal (VariableName, VendorGuid, VariableStoreHeader, &VariablePtr);
+  Status =  VariableServiceGetNextVariableInternal (
+              VariableName,
+              VendorGuid,
+              VariableStoreHeader,
+              &VariablePtr,
+              AuthFormat
+              );
   if (!EFI_ERROR (Status)) {
-    VarNameSize = NameSizeOfVariable (VariablePtr);
+    VarNameSize = NameSizeOfVariable (VariablePtr, AuthFormat);
     ASSERT (VarNameSize != 0);
     if (VarNameSize <= *VariableNameSize) {
-      CopyMem (VariableName, GetVariableNamePtr (VariablePtr), VarNameSize);
-      CopyMem (VendorGuid, GetVendorGuidPtr (VariablePtr), sizeof (EFI_GUID));
+      CopyMem (
+        VariableName,
+        GetVariableNamePtr (VariablePtr, AuthFormat),
+        VarNameSize
+        );
+      CopyMem (
+        VendorGuid,
+        GetVendorGuidPtr (VariablePtr, AuthFormat),
+        sizeof (EFI_GUID)
+        );
       Status = EFI_SUCCESS;
     } else {
       Status = EFI_BUFFER_TOO_SMALL;
@@ -2446,6 +2503,9 @@ VariableServiceSetVariable (
   VARIABLE_HEADER                     *NextVariable;
   EFI_PHYSICAL_ADDRESS                Point;
   UINTN                               PayloadSize;
+  BOOLEAN                             AuthFormat;
+
+  AuthFormat = mVariableModuleGlobal->VariableGlobal.AuthFormat;
 
   //
   // Check input parameters.
@@ -2544,7 +2604,8 @@ VariableServiceSetVariable (
   //  bytes for HwErrRec#### variable.
   //
   if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
-    if (StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxHardwareErrorVariableSize) - GetVariableHeaderSize ()) {
+    if (StrSize (VariableName) + PayloadSize >
+        PcdGet32 (PcdMaxHardwareErrorVariableSize) - GetVariableHeaderSize (AuthFormat)) {
       return EFI_INVALID_PARAMETER;
     }
   } else {
@@ -2553,7 +2614,9 @@ VariableServiceSetVariable (
     //  the DataSize is limited to maximum size of Max(Auth|Volatile)VariableSize bytes.
     //
     if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {
-      if (StrSize (VariableName) + PayloadSize > mVariableModuleGlobal->MaxAuthVariableSize - GetVariableHeaderSize ()) {
+      if (StrSize (VariableName) + PayloadSize >
+          mVariableModuleGlobal->MaxAuthVariableSize -
+          GetVariableHeaderSize (AuthFormat)) {
         DEBUG ((DEBUG_ERROR,
           "%a: Failed to set variable '%s' with Guid %g\n",
           __FUNCTION__, VariableName, VendorGuid));
@@ -2562,12 +2625,13 @@ VariableServiceSetVariable (
           "MaxAuthVariableSize(0x%x) - HeaderSize(0x%x)\n",
           StrSize (VariableName), PayloadSize,
           mVariableModuleGlobal->MaxAuthVariableSize,
-          GetVariableHeaderSize ()
+          GetVariableHeaderSize (AuthFormat)
           ));
         return EFI_INVALID_PARAMETER;
       }
     } else if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
-      if (StrSize (VariableName) + PayloadSize > mVariableModuleGlobal->MaxVariableSize - GetVariableHeaderSize ()) {
+      if (StrSize (VariableName) + PayloadSize >
+          mVariableModuleGlobal->MaxVariableSize - GetVariableHeaderSize (AuthFormat)) {
         DEBUG ((DEBUG_ERROR,
           "%a: Failed to set variable '%s' with Guid %g\n",
           __FUNCTION__, VariableName, VendorGuid));
@@ -2576,12 +2640,13 @@ VariableServiceSetVariable (
           "MaxVariableSize(0x%x) - HeaderSize(0x%x)\n",
           StrSize (VariableName), PayloadSize,
           mVariableModuleGlobal->MaxVariableSize,
-          GetVariableHeaderSize ()
+          GetVariableHeaderSize (AuthFormat)
           ));
         return EFI_INVALID_PARAMETER;
       }
     } else {
-      if (StrSize (VariableName) + PayloadSize > mVariableModuleGlobal->MaxVolatileVariableSize - GetVariableHeaderSize ()) {
+      if (StrSize (VariableName) + PayloadSize >
+          mVariableModuleGlobal->MaxVolatileVariableSize - GetVariableHeaderSize (AuthFormat)) {
         DEBUG ((DEBUG_ERROR,
           "%a: Failed to set variable '%s' with Guid %g\n",
           __FUNCTION__, VariableName, VendorGuid));
@@ -2590,7 +2655,7 @@ VariableServiceSetVariable (
           "MaxVolatileVariableSize(0x%x) - HeaderSize(0x%x)\n",
           StrSize (VariableName), PayloadSize,
           mVariableModuleGlobal->MaxVolatileVariableSize,
-          GetVariableHeaderSize ()
+          GetVariableHeaderSize (AuthFormat)
           ));
         return EFI_INVALID_PARAMETER;
       }
@@ -2629,7 +2694,7 @@ VariableServiceSetVariable (
     //
     NextVariable  = GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point);
     while (IsValidVariableHeader (NextVariable, GetEndPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point))) {
-      NextVariable = GetNextVariablePtr (NextVariable);
+      NextVariable = GetNextVariablePtr (NextVariable, AuthFormat);
     }
     mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) Point;
   }
@@ -2754,7 +2819,8 @@ VariableServiceQueryVariableInfoInternal (
   //
   if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
     *MaximumVariableStorageSize = PcdGet32 (PcdHwErrStorageSize);
-    *MaximumVariableSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - GetVariableHeaderSize ();
+    *MaximumVariableSize =  PcdGet32 (PcdMaxHardwareErrorVariableSize) -
+                              GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat);
   } else {
     if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
       if (AtRuntime ()) {
@@ -2768,11 +2834,14 @@ VariableServiceQueryVariableInfoInternal (
     // Let *MaximumVariableSize be Max(Auth|Volatile)VariableSize with the exception of the variable header size.
     //
     if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) {
-      *MaximumVariableSize = mVariableModuleGlobal->MaxAuthVariableSize - GetVariableHeaderSize ();
+      *MaximumVariableSize =  mVariableModuleGlobal->MaxAuthVariableSize -
+                                GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat);
     } else if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) {
-      *MaximumVariableSize = mVariableModuleGlobal->MaxVariableSize - GetVariableHeaderSize ();
+      *MaximumVariableSize =  mVariableModuleGlobal->MaxVariableSize -
+                                GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat);
     } else {
-      *MaximumVariableSize = mVariableModuleGlobal->MaxVolatileVariableSize - GetVariableHeaderSize ();
+      *MaximumVariableSize =   mVariableModuleGlobal->MaxVolatileVariableSize -
+                                GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat);
     }
   }
 
@@ -2785,7 +2854,7 @@ VariableServiceQueryVariableInfoInternal (
   // Now walk through the related variable store.
   //
   while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) {
-    NextVariable = GetNextVariablePtr (Variable);
+    NextVariable = GetNextVariablePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat);
     VariableSize = (UINT64) (UINTN) NextVariable - (UINT64) (UINTN) Variable;
 
     if (AtRuntime ()) {
@@ -2820,10 +2889,11 @@ VariableServiceQueryVariableInfoInternal (
         VariablePtrTrack.StartPtr = GetStartPointer (VariableStoreHeader);
         VariablePtrTrack.EndPtr   = GetEndPointer   (VariableStoreHeader);
         Status = FindVariableEx (
-                   GetVariableNamePtr (Variable),
-                   GetVendorGuidPtr (Variable),
+                   GetVariableNamePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat),
+                   GetVendorGuidPtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat),
                    FALSE,
-                   &VariablePtrTrack
+                   &VariablePtrTrack,
+                   mVariableModuleGlobal->VariableGlobal.AuthFormat
                    );
         if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State != VAR_ADDED) {
           if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) {
@@ -2851,10 +2921,13 @@ VariableServiceQueryVariableInfoInternal (
     }
   }
 
-  if (*RemainingVariableStorageSize < GetVariableHeaderSize ()) {
+  if (*RemainingVariableStorageSize < GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat)) {
     *MaximumVariableSize = 0;
-  } else if ((*RemainingVariableStorageSize - GetVariableHeaderSize ()) < *MaximumVariableSize) {
-    *MaximumVariableSize = *RemainingVariableStorageSize - GetVariableHeaderSize ();
+  } else if ((*RemainingVariableStorageSize - GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat)) <
+              *MaximumVariableSize
+              ) {
+    *MaximumVariableSize = *RemainingVariableStorageSize -
+                             GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat);
   }
 
   return EFI_SUCCESS;
@@ -3331,7 +3404,7 @@ InitNonVolatileVariableStore (
   //
   Variable  = GetStartPointer (mNvVariableCache);
   while (IsValidVariableHeader (Variable, GetEndPointer (mNvVariableCache))) {
-    NextVariable = GetNextVariablePtr (Variable);
+    NextVariable = GetNextVariablePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat);
     VariableSize = (UINTN) NextVariable - (UINTN) Variable;
     if ((Variable->Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
       mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize;
@@ -3365,8 +3438,10 @@ FlushHobVariableToFlash (
   VOID                          *VariableData;
   VARIABLE_POINTER_TRACK        VariablePtrTrack;
   BOOLEAN                       ErrorFlag;
+  BOOLEAN                       AuthFormat;
 
   ErrorFlag = FALSE;
+  AuthFormat = mVariableModuleGlobal->VariableGlobal.AuthFormat;
 
   //
   // Flush the HOB variable to flash.
@@ -3379,7 +3454,7 @@ FlushHobVariableToFlash (
     mVariableModuleGlobal->VariableGlobal.HobVariableBase = 0;
     for ( Variable = GetStartPointer (VariableStoreHeader)
         ; IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))
-        ; Variable = GetNextVariablePtr (Variable)
+        ; Variable = GetNextVariablePtr (Variable, AuthFormat)
         ) {
       if (Variable->State != VAR_ADDED) {
         //
@@ -3389,22 +3464,33 @@ FlushHobVariableToFlash (
       }
       ASSERT ((Variable->Attributes & EFI_VARIABLE_NON_VOLATILE) != 0);
       if (VendorGuid == NULL || VariableName == NULL ||
-          !CompareGuid (VendorGuid, GetVendorGuidPtr (Variable)) ||
-          StrCmp (VariableName, GetVariableNamePtr (Variable)) != 0) {
-        VariableData = GetVariableDataPtr (Variable);
-        FindVariable (GetVariableNamePtr (Variable), GetVendorGuidPtr (Variable), &VariablePtrTrack, &mVariableModuleGlobal->VariableGlobal, FALSE);
+          !CompareGuid (VendorGuid, GetVendorGuidPtr (Variable, AuthFormat)) ||
+          StrCmp (VariableName, GetVariableNamePtr (Variable, AuthFormat)) != 0) {
+        VariableData = GetVariableDataPtr (Variable, AuthFormat);
+        FindVariable (
+          GetVariableNamePtr (Variable, AuthFormat),
+          GetVendorGuidPtr (Variable, AuthFormat),
+          &VariablePtrTrack,
+          &mVariableModuleGlobal->VariableGlobal, FALSE
+          );
         Status = UpdateVariable (
-                   GetVariableNamePtr (Variable),
-                   GetVendorGuidPtr (Variable),
+                   GetVariableNamePtr (Variable, AuthFormat),
+                   GetVendorGuidPtr (Variable, AuthFormat),
                    VariableData,
-                   DataSizeOfVariable (Variable),
+                   DataSizeOfVariable (Variable, AuthFormat),
                    Variable->Attributes,
                    0,
                    0,
                    &VariablePtrTrack,
                    NULL
                  );
-        DEBUG ((EFI_D_INFO, "Variable driver flush the HOB variable to flash: %g %s %r\n", GetVendorGuidPtr (Variable), GetVariableNamePtr (Variable), Status));
+        DEBUG ((
+          DEBUG_INFO,
+          "Variable driver flush the HOB variable to flash: %g %s %r\n",
+          GetVendorGuidPtr (Variable, AuthFormat),
+          GetVariableNamePtr (Variable, AuthFormat),
+          Status
+          ));
       } else {
         //
         // The updated or deleted variable is matched with this HOB variable.
@@ -3418,7 +3504,12 @@ FlushHobVariableToFlash (
         // If set variable successful, or the updated or deleted variable is matched with the HOB variable,
         // set the HOB variable to DELETED state in local.
         //
-        DEBUG ((EFI_D_INFO, "Variable driver set the HOB variable to DELETED state in local: %g %s\n", GetVendorGuidPtr (Variable), GetVariableNamePtr (Variable)));
+        DEBUG ((
+          DEBUG_INFO,
+          "Variable driver set the HOB variable to DELETED state in local: %g %s\n",
+          GetVendorGuidPtr (Variable, AuthFormat),
+          GetVariableNamePtr (Variable, AuthFormat)
+          ));
         Variable->State &= VAR_DELETED;
       } else {
         ErrorFlag = TRUE;
@@ -3495,7 +3586,8 @@ VariableWriteServiceInitialize (
     // Authenticated variable initialize.
     //
     mAuthContextIn.StructSize = sizeof (AUTH_VAR_LIB_CONTEXT_IN);
-    mAuthContextIn.MaxAuthVariableSize = mVariableModuleGlobal->MaxAuthVariableSize - GetVariableHeaderSize ();
+    mAuthContextIn.MaxAuthVariableSize =  mVariableModuleGlobal->MaxAuthVariableSize -
+                                            GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat);
     Status = AuthVariableLibInitialize (&mAuthContextIn, &mAuthContextOut);
     if (!EFI_ERROR (Status)) {
       DEBUG ((EFI_D_INFO, "Variable driver will work with auth variable support!\n"));
@@ -3574,7 +3666,7 @@ ConvertNormalVarStorageToAuthVarStorage (
       AuthVarStroageSize += StartPtr->NameSize + GET_PAD_SIZE (StartPtr->NameSize);
       AuthVarStroageSize += StartPtr->DataSize + GET_PAD_SIZE (StartPtr->DataSize);
     }
-    StartPtr  = GetNextVariablePtr (StartPtr);
+    StartPtr  = GetNextVariablePtr (StartPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
   }
 
   //
@@ -3608,18 +3700,22 @@ ConvertNormalVarStorageToAuthVarStorage (
       // Copy Variable Name
       //
       NextPtr = (UINT8 *) (AuthStartPtr + 1);
-      CopyMem (NextPtr, GetVariableNamePtr (StartPtr), AuthStartPtr->NameSize);
+      CopyMem (
+        NextPtr,
+        GetVariableNamePtr (StartPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat),
+        AuthStartPtr->NameSize
+        );
       //
       // Copy Variable Data
       //
       NextPtr = NextPtr + AuthStartPtr->NameSize + GET_PAD_SIZE (AuthStartPtr->NameSize);
-      CopyMem (NextPtr, GetVariableDataPtr (StartPtr), AuthStartPtr->DataSize);
+      CopyMem (NextPtr, GetVariableDataPtr (StartPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat), AuthStartPtr->DataSize);
       //
       // Go to next variable
       //
       AuthStartPtr = (AUTHENTICATED_VARIABLE_HEADER *) (NextPtr + AuthStartPtr->DataSize + GET_PAD_SIZE (AuthStartPtr->DataSize));
     }
-    StartPtr = GetNextVariablePtr (StartPtr);
+    StartPtr = GetNextVariablePtr (StartPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
   }
   //
   // Update Auth Storage Header
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c
index c787ddba5b..e865a089d1 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c
@@ -56,8 +56,8 @@ VariableExLibFindVariable (
     return Status;
   }
 
-  AuthVariableInfo->DataSize        = DataSizeOfVariable (Variable.CurrPtr);
-  AuthVariableInfo->Data            = GetVariableDataPtr (Variable.CurrPtr);
+  AuthVariableInfo->DataSize        = DataSizeOfVariable (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
+  AuthVariableInfo->Data            = GetVariableDataPtr (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
   AuthVariableInfo->Attributes      = Variable.CurrPtr->Attributes;
   if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
     AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable.CurrPtr;
@@ -108,7 +108,8 @@ VariableExLibFindNextVariable (
              VariableName,
              VendorGuid,
              VariableStoreHeader,
-             &VariablePtr
+             &VariablePtr,
+             mVariableModuleGlobal->VariableGlobal.AuthFormat
              );
   if (EFI_ERROR (Status)) {
     AuthVariableInfo->VariableName = NULL;
@@ -122,10 +123,10 @@ VariableExLibFindNextVariable (
     return Status;
   }
 
-  AuthVariableInfo->VariableName    = GetVariableNamePtr (VariablePtr);
-  AuthVariableInfo->VendorGuid      = GetVendorGuidPtr (VariablePtr);
-  AuthVariableInfo->DataSize        = DataSizeOfVariable (VariablePtr);
-  AuthVariableInfo->Data            = GetVariableDataPtr (VariablePtr);
+  AuthVariableInfo->VariableName    = GetVariableNamePtr (VariablePtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
+  AuthVariableInfo->VendorGuid      = GetVendorGuidPtr (VariablePtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
+  AuthVariableInfo->DataSize        = DataSizeOfVariable (VariablePtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
+  AuthVariableInfo->Data            = GetVariableDataPtr (VariablePtr, mVariableModuleGlobal->VariableGlobal.AuthFormat);
   AuthVariableInfo->Attributes      = VariablePtr->Attributes;
   if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
     AuthVariablePtr = (AUTHENTICATED_VARIABLE_HEADER *) VariablePtr;
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c
index 870c9e3742..d458f1c608 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c
@@ -78,17 +78,20 @@ GetVariableStoreStatus (
 /**
   This code gets the size of variable header.
 
+  @param[in]  AuthFormat    TRUE indicates authenticated variables are used.
+                            FALSE indicates authenticated variables are not used.
+
   @return Size of variable header in bytes in type UINTN.
 
 **/
 UINTN
 GetVariableHeaderSize (
-  VOID
+  IN  BOOLEAN   AuthFormat
   )
 {
   UINTN Value;
 
-  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
+  if (AuthFormat) {
     Value = sizeof (AUTHENTICATED_VARIABLE_HEADER);
   } else {
     Value = sizeof (VARIABLE_HEADER);
@@ -101,20 +104,23 @@ GetVariableHeaderSize (
 
   This code gets the size of name of variable.
 
-  @param Variable        Pointer to the Variable Header.
+  @param[in]  Variable      Pointer to the variable header.
+  @param[in]  AuthFormat    TRUE indicates authenticated variables are used.
+                            FALSE indicates authenticated variables are not used.
 
   @return UINTN          Size of variable in bytes.
 
 **/
 UINTN
 NameSizeOfVariable (
-  IN  VARIABLE_HEADER   *Variable
+  IN  VARIABLE_HEADER   *Variable,
+  IN  BOOLEAN           AuthFormat
   )
 {
   AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
 
   AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
-  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
+  if (AuthFormat) {
     if (AuthVariable->State == (UINT8) (-1) ||
        AuthVariable->DataSize == (UINT32) (-1) ||
        AuthVariable->NameSize == (UINT32) (-1) ||
@@ -136,20 +142,23 @@ NameSizeOfVariable (
 /**
   This code sets the size of name of variable.
 
-  @param[in] Variable   Pointer to the Variable Header.
-  @param[in] NameSize   Name size to set.
+  @param[in]  Variable      Pointer to the Variable Header.
+  @param[in]  NameSize      Name size to set.
+  @param[in]  AuthFormat    TRUE indicates authenticated variables are used.
+                            FALSE indicates authenticated variables are not used.
 
 **/
 VOID
 SetNameSizeOfVariable (
   IN VARIABLE_HEADER    *Variable,
-  IN UINTN              NameSize
+  IN UINTN              NameSize,
+  IN BOOLEAN            AuthFormat
   )
 {
   AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
 
   AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
-  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
+  if (AuthFormat) {
     AuthVariable->NameSize = (UINT32) NameSize;
   } else {
     Variable->NameSize = (UINT32) NameSize;
@@ -160,20 +169,23 @@ SetNameSizeOfVariable (
 
   This code gets the size of variable data.
 
-  @param Variable        Pointer to the Variable Header.
+  @param[in]  Variable      Pointer to the Variable Header.
+  @param[in]  AuthFormat    TRUE indicates authenticated variables are used.
+                            FALSE indicates authenticated variables are not used.
 
   @return Size of variable in bytes.
 
 **/
 UINTN
 DataSizeOfVariable (
-  IN  VARIABLE_HEADER   *Variable
+  IN  VARIABLE_HEADER   *Variable,
+  IN  BOOLEAN           AuthFormat
   )
 {
   AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
 
   AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
-  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
+  if (AuthFormat) {
     if (AuthVariable->State == (UINT8) (-1) ||
        AuthVariable->DataSize == (UINT32) (-1) ||
        AuthVariable->NameSize == (UINT32) (-1) ||
@@ -197,18 +209,21 @@ DataSizeOfVariable (
 
   @param[in] Variable   Pointer to the Variable Header.
   @param[in] DataSize   Data size to set.
+  @param[in] AuthFormat TRUE indicates authenticated variables are used.
+                        FALSE indicates authenticated variables are not used.
 
 **/
 VOID
 SetDataSizeOfVariable (
-  IN VARIABLE_HEADER    *Variable,
-  IN UINTN              DataSize
+  IN  VARIABLE_HEADER   *Variable,
+  IN  UINTN             DataSize,
+  IN  BOOLEAN           AuthFormat
   )
 {
   AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
 
   AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
-  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
+  if (AuthFormat) {
     AuthVariable->DataSize = (UINT32) DataSize;
   } else {
     Variable->DataSize = (UINT32) DataSize;
@@ -219,36 +234,42 @@ SetDataSizeOfVariable (
 
   This code gets the pointer to the variable name.
 
-  @param Variable        Pointer to the Variable Header.
+  @param[in] Variable     Pointer to the Variable Header.
+  @param[in] AuthFormat   TRUE indicates authenticated variables are used.
+                          FALSE indicates authenticated variables are not used.
 
   @return Pointer to Variable Name which is Unicode encoding.
 
 **/
 CHAR16 *
 GetVariableNamePtr (
-  IN  VARIABLE_HEADER   *Variable
+  IN  VARIABLE_HEADER   *Variable,
+  IN  BOOLEAN           AuthFormat
   )
 {
-  return (CHAR16 *) ((UINTN) Variable + GetVariableHeaderSize ());
+  return (CHAR16 *) ((UINTN) Variable + GetVariableHeaderSize (AuthFormat));
 }
 
 /**
   This code gets the pointer to the variable guid.
 
-  @param Variable   Pointer to the Variable Header.
+  @param[in] Variable     Pointer to the Variable Header.
+  @param[in] AuthFormat   TRUE indicates authenticated variables are used.
+                          FALSE indicates authenticated variables are not used.
 
   @return A EFI_GUID* pointer to Vendor Guid.
 
 **/
 EFI_GUID *
 GetVendorGuidPtr (
-  IN VARIABLE_HEADER    *Variable
+  IN  VARIABLE_HEADER    *Variable,
+  IN  BOOLEAN            AuthFormat
   )
 {
   AUTHENTICATED_VARIABLE_HEADER *AuthVariable;
 
   AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable;
-  if (mVariableModuleGlobal->VariableGlobal.AuthFormat) {
+  if (AuthFormat) {
     return &AuthVariable->VendorGuid;
   } else {
     return &Variable->VendorGuid;
@@ -259,14 +280,17 @@ GetVendorGuidPtr (
 
   This code gets the pointer to the variable data.
 
-  @param Variable        Pointer to the Variable Header.
+  @param[in] Variable     Pointer to the Variable Header.
+  @param[in] AuthFormat   TRUE indicates authenticated variables are used.
+                          FALSE indicates authenticated variables are not used.
 
   @return Pointer to Variable Data.
 
 **/
 UINT8 *
 GetVariableDataPtr (
-  IN  VARIABLE_HEADER   *Variable
+  IN  VARIABLE_HEADER    *Variable,
+  IN  BOOLEAN            AuthFormat
   )
 {
   UINTN Value;
@@ -274,9 +298,9 @@ GetVariableDataPtr (
   //
   // Be careful about pad size for alignment.
   //
-  Value =  (UINTN) GetVariableNamePtr (Variable);
-  Value += NameSizeOfVariable (Variable);
-  Value += GET_PAD_SIZE (NameSizeOfVariable (Variable));
+  Value =  (UINTN) GetVariableNamePtr (Variable, AuthFormat);
+  Value += NameSizeOfVariable (Variable, AuthFormat);
+  Value += GET_PAD_SIZE (NameSizeOfVariable (Variable, AuthFormat));
 
   return (UINT8 *) Value;
 }
@@ -284,14 +308,17 @@ GetVariableDataPtr (
 /**
   This code gets the variable data offset related to variable header.
 
-  @param Variable        Pointer to the Variable Header.
+  @param[in] Variable     Pointer to the Variable Header.
+  @param[in] AuthFormat   TRUE indicates authenticated variables are used.
+                          FALSE indicates authenticated variables are not used.
 
   @return Variable Data offset.
 
 **/
 UINTN
 GetVariableDataOffset (
-  IN  VARIABLE_HEADER   *Variable
+  IN  VARIABLE_HEADER   *Variable,
+  IN  BOOLEAN           AuthFormat
   )
 {
   UINTN Value;
@@ -299,9 +326,9 @@ GetVariableDataOffset (
   //
   // Be careful about pad size for alignment
   //
-  Value = GetVariableHeaderSize ();
-  Value += NameSizeOfVariable (Variable);
-  Value += GET_PAD_SIZE (NameSizeOfVariable (Variable));
+  Value = GetVariableHeaderSize (AuthFormat);
+  Value += NameSizeOfVariable (Variable, AuthFormat);
+  Value += GET_PAD_SIZE (NameSizeOfVariable (Variable, AuthFormat));
 
   return Value;
 }
@@ -310,21 +337,24 @@ GetVariableDataOffset (
 
   This code gets the pointer to the next variable header.
 
-  @param Variable        Pointer to the Variable Header.
+  @param[in] Variable     Pointer to the Variable Header.
+  @param[in] AuthFormat   TRUE indicates authenticated variables are used.
+                          FALSE indicates authenticated variables are not used.
 
   @return Pointer to next variable header.
 
 **/
 VARIABLE_HEADER *
 GetNextVariablePtr (
-  IN  VARIABLE_HEADER   *Variable
+  IN  VARIABLE_HEADER   *Variable,
+  IN  BOOLEAN           AuthFormat
   )
 {
   UINTN Value;
 
-  Value =  (UINTN) GetVariableDataPtr (Variable);
-  Value += DataSizeOfVariable (Variable);
-  Value += GET_PAD_SIZE (DataSizeOfVariable (Variable));
+  Value =  (UINTN) GetVariableDataPtr (Variable, AuthFormat);
+  Value += DataSizeOfVariable (Variable, AuthFormat);
+  Value += GET_PAD_SIZE (DataSizeOfVariable (Variable, AuthFormat));
 
   //
   // Be careful about pad size for alignment.
@@ -415,6 +445,8 @@ VariableCompareTimeStampInternal (
   @param[in]       IgnoreRtCheck       Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute
                                        check at runtime when searching variable.
   @param[in, out]  PtrTrack            Variable Track Pointer structure that contains Variable Information.
+  @param[in]       AuthFormat          TRUE indicates authenticated variables are used.
+                                       FALSE indicates authenticated variables are not used.
 
   @retval          EFI_SUCCESS         Variable found successfully
   @retval          EFI_NOT_FOUND       Variable not found
@@ -424,7 +456,8 @@ FindVariableEx (
   IN     CHAR16                  *VariableName,
   IN     EFI_GUID                *VendorGuid,
   IN     BOOLEAN                 IgnoreRtCheck,
-  IN OUT VARIABLE_POINTER_TRACK  *PtrTrack
+  IN OUT VARIABLE_POINTER_TRACK  *PtrTrack,
+  IN     BOOLEAN                 AuthFormat
   )
 {
   VARIABLE_HEADER                *InDeletedVariable;
@@ -439,7 +472,7 @@ FindVariableEx (
 
   for ( PtrTrack->CurrPtr = PtrTrack->StartPtr
       ; IsValidVariableHeader (PtrTrack->CurrPtr, PtrTrack->EndPtr)
-      ; PtrTrack->CurrPtr = GetNextVariablePtr (PtrTrack->CurrPtr)
+      ; PtrTrack->CurrPtr = GetNextVariablePtr (PtrTrack->CurrPtr, AuthFormat)
       ) {
     if (PtrTrack->CurrPtr->State == VAR_ADDED ||
         PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)
@@ -453,11 +486,11 @@ FindVariableEx (
             return EFI_SUCCESS;
           }
         } else {
-          if (CompareGuid (VendorGuid, GetVendorGuidPtr (PtrTrack->CurrPtr))) {
-            Point = (VOID *) GetVariableNamePtr (PtrTrack->CurrPtr);
+          if (CompareGuid (VendorGuid, GetVendorGuidPtr (PtrTrack->CurrPtr, AuthFormat))) {
+            Point = (VOID *) GetVariableNamePtr (PtrTrack->CurrPtr, AuthFormat);
 
-            ASSERT (NameSizeOfVariable (PtrTrack->CurrPtr) != 0);
-            if (CompareMem (VariableName, Point, NameSizeOfVariable (PtrTrack->CurrPtr)) == 0) {
+            ASSERT (NameSizeOfVariable (PtrTrack->CurrPtr, AuthFormat) != 0);
+            if (CompareMem (VariableName, Point, NameSizeOfVariable (PtrTrack->CurrPtr, AuthFormat)) == 0) {
               if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
                 InDeletedVariable     = PtrTrack->CurrPtr;
               } else {
@@ -486,6 +519,8 @@ FindVariableEx (
   @param[in]  VariableStoreList A list of variable stores that should be used to get the next variable.
                                 The maximum number of entries is the max value of VARIABLE_STORE_TYPE.
   @param[out] VariablePtr       Pointer to variable header address.
+  @param[in]  AuthFormat        TRUE indicates authenticated variables are used.
+                                FALSE indicates authenticated variables are not used.
 
   @retval EFI_SUCCESS           The function completed successfully.
   @retval EFI_NOT_FOUND         The next variable was not found.
@@ -500,7 +535,8 @@ VariableServiceGetNextVariableInternal (
   IN  CHAR16                *VariableName,
   IN  EFI_GUID              *VendorGuid,
   IN  VARIABLE_STORE_HEADER **VariableStoreList,
-  OUT VARIABLE_HEADER       **VariablePtr
+  OUT VARIABLE_HEADER       **VariablePtr,
+  IN  BOOLEAN               AuthFormat
   )
 {
   EFI_STATUS              Status;
@@ -525,7 +561,7 @@ VariableServiceGetNextVariableInternal (
     Variable.EndPtr   = GetEndPointer   (VariableStoreList[StoreType]);
     Variable.Volatile = (BOOLEAN) (StoreType == VariableStoreTypeVolatile);
 
-    Status = FindVariableEx (VariableName, VendorGuid, FALSE, &Variable);
+    Status = FindVariableEx (VariableName, VendorGuid, FALSE, &Variable, AuthFormat);
     if (!EFI_ERROR (Status)) {
       break;
     }
@@ -552,7 +588,7 @@ VariableServiceGetNextVariableInternal (
     //
     // If variable name is not empty, get next variable.
     //
-    Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
+    Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr, AuthFormat);
   }
 
   while (TRUE) {
@@ -605,13 +641,14 @@ VariableServiceGetNextVariableInternal (
           VariablePtrTrack.StartPtr = Variable.StartPtr;
           VariablePtrTrack.EndPtr = Variable.EndPtr;
           Status = FindVariableEx (
-                     GetVariableNamePtr (Variable.CurrPtr),
-                     GetVendorGuidPtr (Variable.CurrPtr),
+                     GetVariableNamePtr (Variable.CurrPtr, AuthFormat),
+                     GetVendorGuidPtr (Variable.CurrPtr, AuthFormat),
                      FALSE,
-                     &VariablePtrTrack
+                     &VariablePtrTrack,
+                     AuthFormat
                      );
           if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State == VAR_ADDED) {
-            Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
+            Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr, AuthFormat);
             continue;
           }
         }
@@ -625,13 +662,14 @@ VariableServiceGetNextVariableInternal (
           VariableInHob.StartPtr = GetStartPointer (VariableStoreList[VariableStoreTypeHob]);
           VariableInHob.EndPtr   = GetEndPointer   (VariableStoreList[VariableStoreTypeHob]);
           Status = FindVariableEx (
-                     GetVariableNamePtr (Variable.CurrPtr),
-                     GetVendorGuidPtr (Variable.CurrPtr),
+                     GetVariableNamePtr (Variable.CurrPtr, AuthFormat),
+                     GetVendorGuidPtr (Variable.CurrPtr, AuthFormat),
                      FALSE,
-                     &VariableInHob
+                     &VariableInHob,
+                     AuthFormat
                      );
           if (!EFI_ERROR (Status)) {
-            Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
+            Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr, AuthFormat);
             continue;
           }
         }
@@ -642,7 +680,7 @@ VariableServiceGetNextVariableInternal (
       }
     }
 
-    Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
+    Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr, AuthFormat);
   }
 
 Done:
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c
index ce409f22a3..5e24bc4a62 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c
@@ -975,8 +975,9 @@ MmVariableServiceInitialize (
                     );
   ASSERT_EFI_ERROR (Status);
 
-  mVariableBufferPayloadSize = GetMaxVariableSize () +
-                               OFFSET_OF (SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY, Name) - GetVariableHeaderSize ();
+  mVariableBufferPayloadSize =  GetMaxVariableSize () +
+                                  OFFSET_OF (SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY, Name) -
+                                  GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat);
 
   Status = gMmst->MmAllocatePool (
                     EfiRuntimeServicesData,
-- 
2.16.2.windows.1


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [PATCH V7 05/10] MdeModulePkg/Variable: Add a file for NV variable functions
  2019-11-01 17:34 [PATCH V7 00/10] UEFI Variable SMI Reduction Kubacki, Michael A
                   ` (3 preceding siblings ...)
  2019-11-01 17:34 ` [PATCH V7 04/10] MdeModulePkg/Variable: Parameterize auth status in VariableParsing Kubacki, Michael A
@ 2019-11-01 17:34 ` Kubacki, Michael A
  2019-11-01 17:34 ` [PATCH V7 06/10] MdeModulePkg VariableInfo: Always consider RT DXE and SMM stats Kubacki, Michael A
                   ` (5 subsequent siblings)
  10 siblings, 0 replies; 14+ messages in thread
From: Kubacki, Michael A @ 2019-11-01 17:34 UTC (permalink / raw)
  To: devel
  Cc: Dandan Bi, Ard Biesheuvel, Eric Dong, Laszlo Ersek, Liming Gao,
	Michael D Kinney, Ray Ni, Jian J Wang, Hao A Wu, Jiewen Yao

This change adds a dedicated file for variable operations specific
to non-volatile variables. This decreases the overall length of the
relatively large Variable.c file.

Cc: Dandan Bi <dandan.bi@intel.com>
Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Eric Dong <eric.dong@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Cc: Liming Gao <liming.gao@intel.com>
Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Hao A Wu <hao.a.wu@intel.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Signed-off-by: Michael Kubacki <michael.a.kubacki@intel.com>
---
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf   |   2 +
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf          |   2 +
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf |   2 +
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.h    |  67 ++++
 MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c               | 317 +------------------
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.c    | 334 ++++++++++++++++++++
 6 files changed, 408 insertions(+), 316 deletions(-)

diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
index c35e5fe787..08a5490787 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
@@ -36,6 +36,8 @@
   Variable.c
   VariableDxe.c
   Variable.h
+  VariableNonVolatile.c
+  VariableNonVolatile.h
   VariableParsing.c
   VariableParsing.h
   PrivilegePolymorphic.h
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf
index 626738b9c7..6dc2721b81 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf
@@ -45,6 +45,8 @@
   Variable.c
   VariableTraditionalMm.c
   VariableSmm.c
+  VariableNonVolatile.c
+  VariableNonVolatile.h
   VariableParsing.c
   VariableParsing.h
   VarCheck.c
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf
index ff714b193a..f8a3742959 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf
@@ -45,6 +45,8 @@
   Variable.c
   VariableSmm.c
   VariableStandaloneMm.c
+  VariableNonVolatile.c
+  VariableNonVolatile.h
   VariableParsing.c
   VariableParsing.h
   VarCheck.c
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.h
new file mode 100644
index 0000000000..43653f27e6
--- /dev/null
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.h
@@ -0,0 +1,67 @@
+/** @file
+  Common variable non-volatile store routines.
+
+Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef _VARIABLE_NON_VOLATILE_H_
+#define _VARIABLE_NON_VOLATILE_H_
+
+#include "Variable.h"
+
+/**
+  Get non-volatile maximum variable size.
+
+  @return Non-volatile maximum variable size.
+
+**/
+UINTN
+GetNonVolatileMaxVariableSize (
+  VOID
+  );
+
+/**
+  Init emulated non-volatile variable store.
+
+  @param[out] VariableStoreBase Output pointer to emulated non-volatile variable store base.
+
+  @retval EFI_SUCCESS           Function successfully executed.
+  @retval EFI_OUT_OF_RESOURCES  Fail to allocate enough memory resource.
+
+**/
+EFI_STATUS
+InitEmuNonVolatileVariableStore (
+  EFI_PHYSICAL_ADDRESS  *VariableStoreBase
+  );
+
+/**
+  Init real non-volatile variable store.
+
+  @param[out] VariableStoreBase Output pointer to real non-volatile variable store base.
+
+  @retval EFI_SUCCESS           Function successfully executed.
+  @retval EFI_OUT_OF_RESOURCES  Fail to allocate enough memory resource.
+  @retval EFI_VOLUME_CORRUPTED  Variable Store or Firmware Volume for Variable Store is corrupted.
+
+**/
+EFI_STATUS
+InitRealNonVolatileVariableStore (
+  OUT EFI_PHYSICAL_ADDRESS              *VariableStoreBase
+  );
+
+/**
+  Init non-volatile variable store.
+
+  @retval EFI_SUCCESS           Function successfully executed.
+  @retval EFI_OUT_OF_RESOURCES  Fail to allocate enough memory resource.
+  @retval EFI_VOLUME_CORRUPTED  Variable Store or Firmware Volume for Variable Store is corrupted.
+
+**/
+EFI_STATUS
+InitNonVolatileVariableStore (
+  VOID
+  );
+
+#endif
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
index 2e32905dfe..0bd2f22e1a 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
@@ -23,6 +23,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 **/
 
 #include "Variable.h"
+#include "VariableNonVolatile.h"
 #include "VariableParsing.h"
 
 VARIABLE_MODULE_GLOBAL  *mVariableModuleGlobal;
@@ -3079,25 +3080,6 @@ ReclaimForOS(
   }
 }
 
-/**
-  Get non-volatile maximum variable size.
-
-  @return Non-volatile maximum variable size.
-
-**/
-UINTN
-GetNonVolatileMaxVariableSize (
-  VOID
-  )
-{
-  if (PcdGet32 (PcdHwErrStorageSize) != 0) {
-    return MAX (MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxAuthVariableSize)),
-                PcdGet32 (PcdMaxHardwareErrorVariableSize));
-  } else {
-    return MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxAuthVariableSize));
-  }
-}
-
 /**
   Get maximum variable size, covering both non-volatile and volatile variables.
 
@@ -3122,303 +3104,6 @@ GetMaxVariableSize (
   return MaxVariableSize;
 }
 
-/**
-  Init real non-volatile variable store.
-
-  @param[out] VariableStoreBase Output pointer to real non-volatile variable store base.
-
-  @retval EFI_SUCCESS           Function successfully executed.
-  @retval EFI_OUT_OF_RESOURCES  Fail to allocate enough memory resource.
-  @retval EFI_VOLUME_CORRUPTED  Variable Store or Firmware Volume for Variable Store is corrupted.
-
-**/
-EFI_STATUS
-InitRealNonVolatileVariableStore (
-  OUT EFI_PHYSICAL_ADDRESS              *VariableStoreBase
-  )
-{
-  EFI_FIRMWARE_VOLUME_HEADER            *FvHeader;
-  VARIABLE_STORE_HEADER                 *VariableStore;
-  UINT32                                VariableStoreLength;
-  EFI_HOB_GUID_TYPE                     *GuidHob;
-  EFI_PHYSICAL_ADDRESS                  NvStorageBase;
-  UINT8                                 *NvStorageData;
-  UINT32                                NvStorageSize;
-  FAULT_TOLERANT_WRITE_LAST_WRITE_DATA  *FtwLastWriteData;
-  UINT32                                BackUpOffset;
-  UINT32                                BackUpSize;
-  UINT32                                HwErrStorageSize;
-  UINT32                                MaxUserNvVariableSpaceSize;
-  UINT32                                BoottimeReservedNvVariableSpaceSize;
-  EFI_STATUS                            Status;
-  VOID                                  *FtwProtocol;
-
-  mVariableModuleGlobal->FvbInstance = NULL;
-
-  //
-  // Allocate runtime memory used for a memory copy of the FLASH region.
-  // Keep the memory and the FLASH in sync as updates occur.
-  //
-  NvStorageSize = PcdGet32 (PcdFlashNvStorageVariableSize);
-  NvStorageData = AllocateRuntimeZeroPool (NvStorageSize);
-  if (NvStorageData == NULL) {
-    return EFI_OUT_OF_RESOURCES;
-  }
-
-  NvStorageBase = NV_STORAGE_VARIABLE_BASE;
-  ASSERT (NvStorageBase != 0);
-
-  //
-  // Copy NV storage data to the memory buffer.
-  //
-  CopyMem (NvStorageData, (UINT8 *) (UINTN) NvStorageBase, NvStorageSize);
-
-  Status = GetFtwProtocol ((VOID **)&FtwProtocol);
-  //
-  // If FTW protocol has been installed, no need to check FTW last write data hob.
-  //
-  if (EFI_ERROR (Status)) {
-    //
-    // Check the FTW last write data hob.
-    //
-    GuidHob = GetFirstGuidHob (&gEdkiiFaultTolerantWriteGuid);
-    if (GuidHob != NULL) {
-      FtwLastWriteData = (FAULT_TOLERANT_WRITE_LAST_WRITE_DATA *) GET_GUID_HOB_DATA (GuidHob);
-      if (FtwLastWriteData->TargetAddress == NvStorageBase) {
-        DEBUG ((EFI_D_INFO, "Variable: NV storage is backed up in spare block: 0x%x\n", (UINTN) FtwLastWriteData->SpareAddress));
-        //
-        // Copy the backed up NV storage data to the memory buffer from spare block.
-        //
-        CopyMem (NvStorageData, (UINT8 *) (UINTN) (FtwLastWriteData->SpareAddress), NvStorageSize);
-      } else if ((FtwLastWriteData->TargetAddress > NvStorageBase) &&
-                 (FtwLastWriteData->TargetAddress < (NvStorageBase + NvStorageSize))) {
-        //
-        // Flash NV storage from the Offset is backed up in spare block.
-        //
-        BackUpOffset = (UINT32) (FtwLastWriteData->TargetAddress - NvStorageBase);
-        BackUpSize = NvStorageSize - BackUpOffset;
-        DEBUG ((EFI_D_INFO, "Variable: High partial NV storage from offset: %x is backed up in spare block: 0x%x\n", BackUpOffset, (UINTN) FtwLastWriteData->SpareAddress));
-        //
-        // Copy the partial backed up NV storage data to the memory buffer from spare block.
-        //
-        CopyMem (NvStorageData + BackUpOffset, (UINT8 *) (UINTN) FtwLastWriteData->SpareAddress, BackUpSize);
-      }
-    }
-  }
-
-  FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *) NvStorageData;
-
-  //
-  // Check if the Firmware Volume is not corrupted
-  //
-  if ((FvHeader->Signature != EFI_FVH_SIGNATURE) || (!CompareGuid (&gEfiSystemNvDataFvGuid, &FvHeader->FileSystemGuid))) {
-    FreePool (NvStorageData);
-    DEBUG ((EFI_D_ERROR, "Firmware Volume for Variable Store is corrupted\n"));
-    return EFI_VOLUME_CORRUPTED;
-  }
-
-  VariableStore = (VARIABLE_STORE_HEADER *) ((UINTN) FvHeader + FvHeader->HeaderLength);
-  VariableStoreLength = NvStorageSize - FvHeader->HeaderLength;
-  ASSERT (sizeof (VARIABLE_STORE_HEADER) <= VariableStoreLength);
-  ASSERT (VariableStore->Size == VariableStoreLength);
-
-  //
-  // Check if the Variable Store header is not corrupted
-  //
-  if (GetVariableStoreStatus (VariableStore) != EfiValid) {
-    FreePool (NvStorageData);
-    DEBUG((EFI_D_ERROR, "Variable Store header is corrupted\n"));
-    return EFI_VOLUME_CORRUPTED;
-  }
-
-  mNvFvHeaderCache = FvHeader;
-
-  *VariableStoreBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStore;
-
-  HwErrStorageSize = PcdGet32 (PcdHwErrStorageSize);
-  MaxUserNvVariableSpaceSize = PcdGet32 (PcdMaxUserNvVariableSpaceSize);
-  BoottimeReservedNvVariableSpaceSize = PcdGet32 (PcdBoottimeReservedNvVariableSpaceSize);
-
-  //
-  // Note that in EdkII variable driver implementation, Hardware Error Record type variable
-  // is stored with common variable in the same NV region. So the platform integrator should
-  // ensure that the value of PcdHwErrStorageSize is less than the value of
-  // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)).
-  //
-  ASSERT (HwErrStorageSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)));
-  //
-  // Ensure that the value of PcdMaxUserNvVariableSpaceSize is less than the value of
-  // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize).
-  //
-  ASSERT (MaxUserNvVariableSpaceSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize));
-  //
-  // Ensure that the value of PcdBoottimeReservedNvVariableSpaceSize is less than the value of
-  // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize).
-  //
-  ASSERT (BoottimeReservedNvVariableSpaceSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize));
-
-  mVariableModuleGlobal->CommonVariableSpace = ((UINTN) VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize);
-  mVariableModuleGlobal->CommonMaxUserVariableSpace = ((MaxUserNvVariableSpaceSize != 0) ? MaxUserNvVariableSpaceSize : mVariableModuleGlobal->CommonVariableSpace);
-  mVariableModuleGlobal->CommonRuntimeVariableSpace = mVariableModuleGlobal->CommonVariableSpace - BoottimeReservedNvVariableSpaceSize;
-
-  DEBUG ((EFI_D_INFO, "Variable driver common space: 0x%x 0x%x 0x%x\n", mVariableModuleGlobal->CommonVariableSpace, mVariableModuleGlobal->CommonMaxUserVariableSpace, mVariableModuleGlobal->CommonRuntimeVariableSpace));
-
-  //
-  // The max NV variable size should be < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)).
-  //
-  ASSERT (GetNonVolatileMaxVariableSize () < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)));
-
-  return EFI_SUCCESS;
-}
-
-/**
-  Init emulated non-volatile variable store.
-
-  @param[out] VariableStoreBase Output pointer to emulated non-volatile variable store base.
-
-  @retval EFI_SUCCESS           Function successfully executed.
-  @retval EFI_OUT_OF_RESOURCES  Fail to allocate enough memory resource.
-
-**/
-EFI_STATUS
-InitEmuNonVolatileVariableStore (
-  EFI_PHYSICAL_ADDRESS  *VariableStoreBase
-  )
-{
-  VARIABLE_STORE_HEADER *VariableStore;
-  UINT32                VariableStoreLength;
-  BOOLEAN               FullyInitializeStore;
-  UINT32                HwErrStorageSize;
-
-  FullyInitializeStore = TRUE;
-
-  VariableStoreLength = PcdGet32 (PcdVariableStoreSize);
-  ASSERT (sizeof (VARIABLE_STORE_HEADER) <= VariableStoreLength);
-
-  //
-  // Allocate memory for variable store.
-  //
-  if (PcdGet64 (PcdEmuVariableNvStoreReserved) == 0) {
-    VariableStore = (VARIABLE_STORE_HEADER *) AllocateRuntimePool (VariableStoreLength);
-    if (VariableStore == NULL) {
-      return EFI_OUT_OF_RESOURCES;
-    }
-  } else {
-    //
-    // A memory location has been reserved for the NV variable store.  Certain
-    // platforms may be able to preserve a memory range across system resets,
-    // thereby providing better NV variable emulation.
-    //
-    VariableStore =
-      (VARIABLE_STORE_HEADER *)(VOID*)(UINTN)
-        PcdGet64 (PcdEmuVariableNvStoreReserved);
-    if ((VariableStore->Size == VariableStoreLength) &&
-        (CompareGuid (&VariableStore->Signature, &gEfiAuthenticatedVariableGuid) ||
-         CompareGuid (&VariableStore->Signature, &gEfiVariableGuid)) &&
-        (VariableStore->Format == VARIABLE_STORE_FORMATTED) &&
-        (VariableStore->State == VARIABLE_STORE_HEALTHY)) {
-      DEBUG((
-        DEBUG_INFO,
-        "Variable Store reserved at %p appears to be valid\n",
-        VariableStore
-        ));
-      FullyInitializeStore = FALSE;
-    }
-  }
-
-  if (FullyInitializeStore) {
-    SetMem (VariableStore, VariableStoreLength, 0xff);
-    //
-    // Use gEfiAuthenticatedVariableGuid for potential auth variable support.
-    //
-    CopyGuid (&VariableStore->Signature, &gEfiAuthenticatedVariableGuid);
-    VariableStore->Size       = VariableStoreLength;
-    VariableStore->Format     = VARIABLE_STORE_FORMATTED;
-    VariableStore->State      = VARIABLE_STORE_HEALTHY;
-    VariableStore->Reserved   = 0;
-    VariableStore->Reserved1  = 0;
-  }
-
-  *VariableStoreBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStore;
-
-  HwErrStorageSize = PcdGet32 (PcdHwErrStorageSize);
-
-  //
-  // Note that in EdkII variable driver implementation, Hardware Error Record type variable
-  // is stored with common variable in the same NV region. So the platform integrator should
-  // ensure that the value of PcdHwErrStorageSize is less than the value of
-  // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)).
-  //
-  ASSERT (HwErrStorageSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)));
-
-  mVariableModuleGlobal->CommonVariableSpace = ((UINTN) VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize);
-  mVariableModuleGlobal->CommonMaxUserVariableSpace = mVariableModuleGlobal->CommonVariableSpace;
-  mVariableModuleGlobal->CommonRuntimeVariableSpace = mVariableModuleGlobal->CommonVariableSpace;
-
-  return EFI_SUCCESS;
-}
-
-/**
-  Init non-volatile variable store.
-
-  @retval EFI_SUCCESS           Function successfully executed.
-  @retval EFI_OUT_OF_RESOURCES  Fail to allocate enough memory resource.
-  @retval EFI_VOLUME_CORRUPTED  Variable Store or Firmware Volume for Variable Store is corrupted.
-
-**/
-EFI_STATUS
-InitNonVolatileVariableStore (
-  VOID
-  )
-{
-  VARIABLE_HEADER                       *Variable;
-  VARIABLE_HEADER                       *NextVariable;
-  EFI_PHYSICAL_ADDRESS                  VariableStoreBase;
-  UINTN                                 VariableSize;
-  EFI_STATUS                            Status;
-
-  if (PcdGetBool (PcdEmuVariableNvModeEnable)) {
-    Status = InitEmuNonVolatileVariableStore (&VariableStoreBase);
-    if (EFI_ERROR (Status)) {
-      return Status;
-    }
-    mVariableModuleGlobal->VariableGlobal.EmuNvMode = TRUE;
-    DEBUG ((DEBUG_INFO, "Variable driver will work at emulated non-volatile variable mode!\n"));
-  } else {
-    Status = InitRealNonVolatileVariableStore (&VariableStoreBase);
-    if (EFI_ERROR (Status)) {
-      return Status;
-    }
-    mVariableModuleGlobal->VariableGlobal.EmuNvMode = FALSE;
-  }
-
-  mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;
-  mNvVariableCache = (VARIABLE_STORE_HEADER *) (UINTN) VariableStoreBase;
-  mVariableModuleGlobal->VariableGlobal.AuthFormat = (BOOLEAN)(CompareGuid (&mNvVariableCache->Signature, &gEfiAuthenticatedVariableGuid));
-
-  mVariableModuleGlobal->MaxVariableSize = PcdGet32 (PcdMaxVariableSize);
-  mVariableModuleGlobal->MaxAuthVariableSize = ((PcdGet32 (PcdMaxAuthVariableSize) != 0) ? PcdGet32 (PcdMaxAuthVariableSize) : mVariableModuleGlobal->MaxVariableSize);
-
-  //
-  // Parse non-volatile variable data and get last variable offset.
-  //
-  Variable  = GetStartPointer (mNvVariableCache);
-  while (IsValidVariableHeader (Variable, GetEndPointer (mNvVariableCache))) {
-    NextVariable = GetNextVariablePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat);
-    VariableSize = (UINTN) NextVariable - (UINTN) Variable;
-    if ((Variable->Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
-      mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize;
-    } else {
-      mVariableModuleGlobal->CommonVariableTotalSize += VariableSize;
-    }
-
-    Variable = NextVariable;
-  }
-  mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) Variable - (UINTN) mNvVariableCache;
-
-  return EFI_SUCCESS;
-}
-
 /**
   Flush the HOB variable to flash.
 
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.c
new file mode 100644
index 0000000000..0637a828b3
--- /dev/null
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.c
@@ -0,0 +1,334 @@
+/** @file
+  Common variable non-volatile store routines.
+
+Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "VariableNonVolatile.h"
+#include "VariableParsing.h"
+
+extern VARIABLE_MODULE_GLOBAL  *mVariableModuleGlobal;
+
+/**
+  Get non-volatile maximum variable size.
+
+  @return Non-volatile maximum variable size.
+
+**/
+UINTN
+GetNonVolatileMaxVariableSize (
+  VOID
+  )
+{
+  if (PcdGet32 (PcdHwErrStorageSize) != 0) {
+    return MAX (MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxAuthVariableSize)),
+                PcdGet32 (PcdMaxHardwareErrorVariableSize));
+  } else {
+    return MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxAuthVariableSize));
+  }
+}
+
+/**
+  Init emulated non-volatile variable store.
+
+  @param[out] VariableStoreBase Output pointer to emulated non-volatile variable store base.
+
+  @retval EFI_SUCCESS           Function successfully executed.
+  @retval EFI_OUT_OF_RESOURCES  Fail to allocate enough memory resource.
+
+**/
+EFI_STATUS
+InitEmuNonVolatileVariableStore (
+  OUT EFI_PHYSICAL_ADDRESS  *VariableStoreBase
+  )
+{
+  VARIABLE_STORE_HEADER *VariableStore;
+  UINT32                VariableStoreLength;
+  BOOLEAN               FullyInitializeStore;
+  UINT32                HwErrStorageSize;
+
+  FullyInitializeStore = TRUE;
+
+  VariableStoreLength = PcdGet32 (PcdVariableStoreSize);
+  ASSERT (sizeof (VARIABLE_STORE_HEADER) <= VariableStoreLength);
+
+  //
+  // Allocate memory for variable store.
+  //
+  if (PcdGet64 (PcdEmuVariableNvStoreReserved) == 0) {
+    VariableStore = (VARIABLE_STORE_HEADER *) AllocateRuntimePool (VariableStoreLength);
+    if (VariableStore == NULL) {
+      return EFI_OUT_OF_RESOURCES;
+    }
+  } else {
+    //
+    // A memory location has been reserved for the NV variable store.  Certain
+    // platforms may be able to preserve a memory range across system resets,
+    // thereby providing better NV variable emulation.
+    //
+    VariableStore =
+      (VARIABLE_STORE_HEADER *)(VOID*)(UINTN)
+        PcdGet64 (PcdEmuVariableNvStoreReserved);
+    if ((VariableStore->Size == VariableStoreLength) &&
+        (CompareGuid (&VariableStore->Signature, &gEfiAuthenticatedVariableGuid) ||
+         CompareGuid (&VariableStore->Signature, &gEfiVariableGuid)) &&
+        (VariableStore->Format == VARIABLE_STORE_FORMATTED) &&
+        (VariableStore->State == VARIABLE_STORE_HEALTHY)) {
+      DEBUG((
+        DEBUG_INFO,
+        "Variable Store reserved at %p appears to be valid\n",
+        VariableStore
+        ));
+      FullyInitializeStore = FALSE;
+    }
+  }
+
+  if (FullyInitializeStore) {
+    SetMem (VariableStore, VariableStoreLength, 0xff);
+    //
+    // Use gEfiAuthenticatedVariableGuid for potential auth variable support.
+    //
+    CopyGuid (&VariableStore->Signature, &gEfiAuthenticatedVariableGuid);
+    VariableStore->Size       = VariableStoreLength;
+    VariableStore->Format     = VARIABLE_STORE_FORMATTED;
+    VariableStore->State      = VARIABLE_STORE_HEALTHY;
+    VariableStore->Reserved   = 0;
+    VariableStore->Reserved1  = 0;
+  }
+
+  *VariableStoreBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStore;
+
+  HwErrStorageSize = PcdGet32 (PcdHwErrStorageSize);
+
+  //
+  // Note that in EdkII variable driver implementation, Hardware Error Record type variable
+  // is stored with common variable in the same NV region. So the platform integrator should
+  // ensure that the value of PcdHwErrStorageSize is less than the value of
+  // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)).
+  //
+  ASSERT (HwErrStorageSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)));
+
+  mVariableModuleGlobal->CommonVariableSpace = ((UINTN) VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize);
+  mVariableModuleGlobal->CommonMaxUserVariableSpace = mVariableModuleGlobal->CommonVariableSpace;
+  mVariableModuleGlobal->CommonRuntimeVariableSpace = mVariableModuleGlobal->CommonVariableSpace;
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Init real non-volatile variable store.
+
+  @param[out] VariableStoreBase Output pointer to real non-volatile variable store base.
+
+  @retval EFI_SUCCESS           Function successfully executed.
+  @retval EFI_OUT_OF_RESOURCES  Fail to allocate enough memory resource.
+  @retval EFI_VOLUME_CORRUPTED  Variable Store or Firmware Volume for Variable Store is corrupted.
+
+**/
+EFI_STATUS
+InitRealNonVolatileVariableStore (
+  OUT EFI_PHYSICAL_ADDRESS              *VariableStoreBase
+  )
+{
+  EFI_FIRMWARE_VOLUME_HEADER            *FvHeader;
+  VARIABLE_STORE_HEADER                 *VariableStore;
+  UINT32                                VariableStoreLength;
+  EFI_HOB_GUID_TYPE                     *GuidHob;
+  EFI_PHYSICAL_ADDRESS                  NvStorageBase;
+  UINT8                                 *NvStorageData;
+  UINT32                                NvStorageSize;
+  FAULT_TOLERANT_WRITE_LAST_WRITE_DATA  *FtwLastWriteData;
+  UINT32                                BackUpOffset;
+  UINT32                                BackUpSize;
+  UINT32                                HwErrStorageSize;
+  UINT32                                MaxUserNvVariableSpaceSize;
+  UINT32                                BoottimeReservedNvVariableSpaceSize;
+  EFI_STATUS                            Status;
+  VOID                                  *FtwProtocol;
+
+  mVariableModuleGlobal->FvbInstance = NULL;
+
+  //
+  // Allocate runtime memory used for a memory copy of the FLASH region.
+  // Keep the memory and the FLASH in sync as updates occur.
+  //
+  NvStorageSize = PcdGet32 (PcdFlashNvStorageVariableSize);
+  NvStorageData = AllocateRuntimeZeroPool (NvStorageSize);
+  if (NvStorageData == NULL) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  NvStorageBase = NV_STORAGE_VARIABLE_BASE;
+  ASSERT (NvStorageBase != 0);
+
+  //
+  // Copy NV storage data to the memory buffer.
+  //
+  CopyMem (NvStorageData, (UINT8 *) (UINTN) NvStorageBase, NvStorageSize);
+
+  Status = GetFtwProtocol ((VOID **)&FtwProtocol);
+  //
+  // If FTW protocol has been installed, no need to check FTW last write data hob.
+  //
+  if (EFI_ERROR (Status)) {
+    //
+    // Check the FTW last write data hob.
+    //
+    GuidHob = GetFirstGuidHob (&gEdkiiFaultTolerantWriteGuid);
+    if (GuidHob != NULL) {
+      FtwLastWriteData = (FAULT_TOLERANT_WRITE_LAST_WRITE_DATA *) GET_GUID_HOB_DATA (GuidHob);
+      if (FtwLastWriteData->TargetAddress == NvStorageBase) {
+        DEBUG ((DEBUG_INFO, "Variable: NV storage is backed up in spare block: 0x%x\n", (UINTN) FtwLastWriteData->SpareAddress));
+        //
+        // Copy the backed up NV storage data to the memory buffer from spare block.
+        //
+        CopyMem (NvStorageData, (UINT8 *) (UINTN) (FtwLastWriteData->SpareAddress), NvStorageSize);
+      } else if ((FtwLastWriteData->TargetAddress > NvStorageBase) &&
+                 (FtwLastWriteData->TargetAddress < (NvStorageBase + NvStorageSize))) {
+        //
+        // Flash NV storage from the Offset is backed up in spare block.
+        //
+        BackUpOffset = (UINT32) (FtwLastWriteData->TargetAddress - NvStorageBase);
+        BackUpSize = NvStorageSize - BackUpOffset;
+        DEBUG ((DEBUG_INFO, "Variable: High partial NV storage from offset: %x is backed up in spare block: 0x%x\n", BackUpOffset, (UINTN) FtwLastWriteData->SpareAddress));
+        //
+        // Copy the partial backed up NV storage data to the memory buffer from spare block.
+        //
+        CopyMem (NvStorageData + BackUpOffset, (UINT8 *) (UINTN) FtwLastWriteData->SpareAddress, BackUpSize);
+      }
+    }
+  }
+
+  FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *) NvStorageData;
+
+  //
+  // Check if the Firmware Volume is not corrupted
+  //
+  if ((FvHeader->Signature != EFI_FVH_SIGNATURE) || (!CompareGuid (&gEfiSystemNvDataFvGuid, &FvHeader->FileSystemGuid))) {
+    FreePool (NvStorageData);
+    DEBUG ((DEBUG_ERROR, "Firmware Volume for Variable Store is corrupted\n"));
+    return EFI_VOLUME_CORRUPTED;
+  }
+
+  VariableStore = (VARIABLE_STORE_HEADER *) ((UINTN) FvHeader + FvHeader->HeaderLength);
+  VariableStoreLength = NvStorageSize - FvHeader->HeaderLength;
+  ASSERT (sizeof (VARIABLE_STORE_HEADER) <= VariableStoreLength);
+  ASSERT (VariableStore->Size == VariableStoreLength);
+
+  //
+  // Check if the Variable Store header is not corrupted
+  //
+  if (GetVariableStoreStatus (VariableStore) != EfiValid) {
+    FreePool (NvStorageData);
+    DEBUG((DEBUG_ERROR, "Variable Store header is corrupted\n"));
+    return EFI_VOLUME_CORRUPTED;
+  }
+
+  mNvFvHeaderCache = FvHeader;
+
+  *VariableStoreBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStore;
+
+  HwErrStorageSize = PcdGet32 (PcdHwErrStorageSize);
+  MaxUserNvVariableSpaceSize = PcdGet32 (PcdMaxUserNvVariableSpaceSize);
+  BoottimeReservedNvVariableSpaceSize = PcdGet32 (PcdBoottimeReservedNvVariableSpaceSize);
+
+  //
+  // Note that in EdkII variable driver implementation, Hardware Error Record type variable
+  // is stored with common variable in the same NV region. So the platform integrator should
+  // ensure that the value of PcdHwErrStorageSize is less than the value of
+  // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)).
+  //
+  ASSERT (HwErrStorageSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)));
+  //
+  // Ensure that the value of PcdMaxUserNvVariableSpaceSize is less than the value of
+  // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize).
+  //
+  ASSERT (MaxUserNvVariableSpaceSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize));
+  //
+  // Ensure that the value of PcdBoottimeReservedNvVariableSpaceSize is less than the value of
+  // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize).
+  //
+  ASSERT (BoottimeReservedNvVariableSpaceSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize));
+
+  mVariableModuleGlobal->CommonVariableSpace = ((UINTN) VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize);
+  mVariableModuleGlobal->CommonMaxUserVariableSpace = ((MaxUserNvVariableSpaceSize != 0) ? MaxUserNvVariableSpaceSize : mVariableModuleGlobal->CommonVariableSpace);
+  mVariableModuleGlobal->CommonRuntimeVariableSpace = mVariableModuleGlobal->CommonVariableSpace - BoottimeReservedNvVariableSpaceSize;
+
+  DEBUG ((
+    DEBUG_INFO,
+    "Variable driver common space: 0x%x 0x%x 0x%x\n",
+    mVariableModuleGlobal->CommonVariableSpace,
+    mVariableModuleGlobal->CommonMaxUserVariableSpace,
+    mVariableModuleGlobal->CommonRuntimeVariableSpace
+    ));
+
+  //
+  // The max NV variable size should be < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)).
+  //
+  ASSERT (GetNonVolatileMaxVariableSize () < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)));
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Init non-volatile variable store.
+
+  @retval EFI_SUCCESS           Function successfully executed.
+  @retval EFI_OUT_OF_RESOURCES  Fail to allocate enough memory resource.
+  @retval EFI_VOLUME_CORRUPTED  Variable Store or Firmware Volume for Variable Store is corrupted.
+
+**/
+EFI_STATUS
+InitNonVolatileVariableStore (
+  VOID
+  )
+{
+  VARIABLE_HEADER                       *Variable;
+  VARIABLE_HEADER                       *NextVariable;
+  EFI_PHYSICAL_ADDRESS                  VariableStoreBase;
+  UINTN                                 VariableSize;
+  EFI_STATUS                            Status;
+
+  if (PcdGetBool (PcdEmuVariableNvModeEnable)) {
+    Status = InitEmuNonVolatileVariableStore (&VariableStoreBase);
+    if (EFI_ERROR (Status)) {
+      return Status;
+    }
+    mVariableModuleGlobal->VariableGlobal.EmuNvMode = TRUE;
+    DEBUG ((DEBUG_INFO, "Variable driver will work at emulated non-volatile variable mode!\n"));
+  } else {
+    Status = InitRealNonVolatileVariableStore (&VariableStoreBase);
+    if (EFI_ERROR (Status)) {
+      return Status;
+    }
+    mVariableModuleGlobal->VariableGlobal.EmuNvMode = FALSE;
+  }
+
+  mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase;
+  mNvVariableCache = (VARIABLE_STORE_HEADER *) (UINTN) VariableStoreBase;
+  mVariableModuleGlobal->VariableGlobal.AuthFormat = (BOOLEAN)(CompareGuid (&mNvVariableCache->Signature, &gEfiAuthenticatedVariableGuid));
+
+  mVariableModuleGlobal->MaxVariableSize = PcdGet32 (PcdMaxVariableSize);
+  mVariableModuleGlobal->MaxAuthVariableSize = ((PcdGet32 (PcdMaxAuthVariableSize) != 0) ? PcdGet32 (PcdMaxAuthVariableSize) : mVariableModuleGlobal->MaxVariableSize);
+
+  //
+  // Parse non-volatile variable data and get last variable offset.
+  //
+  Variable  = GetStartPointer (mNvVariableCache);
+  while (IsValidVariableHeader (Variable, GetEndPointer (mNvVariableCache))) {
+    NextVariable = GetNextVariablePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat);
+    VariableSize = (UINTN) NextVariable - (UINTN) Variable;
+    if ((Variable->Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
+      mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize;
+    } else {
+      mVariableModuleGlobal->CommonVariableTotalSize += VariableSize;
+    }
+
+    Variable = NextVariable;
+  }
+  mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) Variable - (UINTN) mNvVariableCache;
+
+  return EFI_SUCCESS;
+}
-- 
2.16.2.windows.1


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [PATCH V7 06/10] MdeModulePkg VariableInfo: Always consider RT DXE and SMM stats
  2019-11-01 17:34 [PATCH V7 00/10] UEFI Variable SMI Reduction Kubacki, Michael A
                   ` (4 preceding siblings ...)
  2019-11-01 17:34 ` [PATCH V7 05/10] MdeModulePkg/Variable: Add a file for NV variable functions Kubacki, Michael A
@ 2019-11-01 17:34 ` Kubacki, Michael A
  2019-11-01 17:34 ` [PATCH V7 07/10] MdeModulePkg/Variable: Add RT GetVariable() cache support Kubacki, Michael A
                   ` (4 subsequent siblings)
  10 siblings, 0 replies; 14+ messages in thread
From: Kubacki, Michael A @ 2019-11-01 17:34 UTC (permalink / raw)
  To: devel
  Cc: Dandan Bi, Ard Biesheuvel, Eric Dong, Laszlo Ersek, Liming Gao,
	Michael D Kinney, Ray Ni, Jian J Wang, Hao A Wu, Jiewen Yao

REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2220

The current VariableInfo application only checks for variable
statistics from SMM if the variable information entries are
not present in the UEFI System Configuration table as published
by the DXE UEFI variable driver (VariableRuntimeDxe).

This change first checks for variable information entries in the
UEFI System Configuration but always checks for entries in SMM
as well. If the SMM variable driver is not present, an instance of
EFI_SMM_VARIABLE_PROTOCOL will not be found and the search for
SMM variable statistics will be aborted (an SW SMI to get variable
statistics will not be triggered).

In the case variable statistics are provided by both a Runtime DXE
driver (e.g. VariableSmmRuntimeDxe) and a SMM driver (VariableSmm),
this change will clearly identify statistics from each respective
driver.

Cc: Dandan Bi <dandan.bi@intel.com>
Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Eric Dong <eric.dong@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Cc: Liming Gao <liming.gao@intel.com>
Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Hao A Wu <hao.a.wu@intel.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Signed-off-by: Michael Kubacki <michael.a.kubacki@intel.com>
---
 MdeModulePkg/Application/VariableInfo/VariableInfo.c | 37 ++++++++++----------
 1 file changed, 18 insertions(+), 19 deletions(-)

diff --git a/MdeModulePkg/Application/VariableInfo/VariableInfo.c b/MdeModulePkg/Application/VariableInfo/VariableInfo.c
index f213471e9a..c04ba18213 100644
--- a/MdeModulePkg/Application/VariableInfo/VariableInfo.c
+++ b/MdeModulePkg/Application/VariableInfo/VariableInfo.c
@@ -3,7 +3,7 @@
   this utility will print out the statistics information. You can use console
   redirection to capture the data.
 
-  Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>
+  Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.<BR>
   SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
@@ -126,7 +126,7 @@ PrintInfoFromSmm (
   ASSERT (CommBuffer != NULL);
   ZeroMem (CommBuffer, RealCommSize);
 
-  Print (L"Non-Volatile SMM Variables:\n");
+  Print (L"SMM Driver Non-Volatile Variables:\n");
   do {
     CommSize = RealCommSize;
     Status = GetVariableStatisticsData (CommBuffer, &CommSize);
@@ -155,7 +155,7 @@ PrintInfoFromSmm (
     }
   } while (TRUE);
 
-  Print (L"Volatile SMM Variables:\n");
+  Print (L"SMM Driver Volatile Variables:\n");
   ZeroMem (CommBuffer, RealCommSize);
   do {
     CommSize = RealCommSize;
@@ -207,24 +207,18 @@ UefiMain (
   IN EFI_SYSTEM_TABLE  *SystemTable
   )
 {
-  EFI_STATUS            Status;
+  EFI_STATUS            RuntimeDxeStatus;
+  EFI_STATUS            SmmStatus;
   VARIABLE_INFO_ENTRY   *VariableInfo;
   VARIABLE_INFO_ENTRY   *Entry;
 
-  Status = EfiGetSystemConfigurationTable (&gEfiVariableGuid, (VOID **)&Entry);
-  if (EFI_ERROR (Status) || (Entry == NULL)) {
-    Status = EfiGetSystemConfigurationTable (&gEfiAuthenticatedVariableGuid, (VOID **)&Entry);
+  RuntimeDxeStatus = EfiGetSystemConfigurationTable (&gEfiVariableGuid, (VOID **) &Entry);
+  if (EFI_ERROR (RuntimeDxeStatus) || (Entry == NULL)) {
+    RuntimeDxeStatus = EfiGetSystemConfigurationTable (&gEfiAuthenticatedVariableGuid, (VOID **) &Entry);
   }
 
-  if (EFI_ERROR (Status) || (Entry == NULL)) {
-    Status = PrintInfoFromSmm ();
-    if (!EFI_ERROR (Status)) {
-      return Status;
-    }
-  }
-
-  if (!EFI_ERROR (Status) && (Entry != NULL)) {
-    Print (L"Non-Volatile EFI Variables:\n");
+  if (!EFI_ERROR (RuntimeDxeStatus) && (Entry != NULL)) {
+    Print (L"Runtime DXE Driver Non-Volatile EFI Variables:\n");
     VariableInfo = Entry;
     do {
       if (!VariableInfo->Volatile) {
@@ -242,7 +236,7 @@ UefiMain (
       VariableInfo = VariableInfo->Next;
     } while (VariableInfo != NULL);
 
-    Print (L"Volatile EFI Variables:\n");
+    Print (L"Runtime DXE Driver Volatile EFI Variables:\n");
     VariableInfo = Entry;
     do {
       if (VariableInfo->Volatile) {
@@ -258,14 +252,19 @@ UefiMain (
       }
       VariableInfo = VariableInfo->Next;
     } while (VariableInfo != NULL);
+  }
 
-  } else {
+  SmmStatus = PrintInfoFromSmm ();
+
+  if (EFI_ERROR (RuntimeDxeStatus) && EFI_ERROR (SmmStatus)) {
     Print (L"Warning: Variable Dxe/Smm driver doesn't enable the feature of statistical information!\n");
     Print (L"If you want to see this info, please:\n");
     Print (L"  1. Set PcdVariableCollectStatistics as TRUE\n");
     Print (L"  2. Rebuild Variable Dxe/Smm driver\n");
     Print (L"  3. Run \"VariableInfo\" cmd again\n");
+
+    return EFI_NOT_FOUND;
   }
 
-  return Status;
+  return EFI_SUCCESS;
 }
-- 
2.16.2.windows.1


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [PATCH V7 07/10] MdeModulePkg/Variable: Add RT GetVariable() cache support
  2019-11-01 17:34 [PATCH V7 00/10] UEFI Variable SMI Reduction Kubacki, Michael A
                   ` (5 preceding siblings ...)
  2019-11-01 17:34 ` [PATCH V7 06/10] MdeModulePkg VariableInfo: Always consider RT DXE and SMM stats Kubacki, Michael A
@ 2019-11-01 17:34 ` Kubacki, Michael A
  2019-11-02  1:36   ` Wang, Jian J
  2019-11-01 17:34 ` [PATCH V7 08/10] MdeModulePkg/Variable: Add RT GetNextVariableName() " Kubacki, Michael A
                   ` (3 subsequent siblings)
  10 siblings, 1 reply; 14+ messages in thread
From: Kubacki, Michael A @ 2019-11-01 17:34 UTC (permalink / raw)
  To: devel
  Cc: Dandan Bi, Ard Biesheuvel, Eric Dong, Laszlo Ersek, Liming Gao,
	Michael D Kinney, Ray Ni, Jian J Wang, Hao A Wu, Jiewen Yao

REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2220

This change reduces SMIs for GetVariable () by maintaining a
UEFI variable cache in Runtime DXE in addition to the pre-
existing cache in SMRAM. When the Runtime Service GetVariable()
is invoked, a Runtime DXE cache is used instead of triggering an
SMI to VariableSmm. This can improve overall system performance
by servicing variable read requests without rendezvousing all
cores into SMM.

The runtime cache  can be disabled with by setting the FeaturePCD
gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache
to FALSE. If the PCD is set to FALSE, the runtime cache will not be
used and an SMI will be triggered for Runtime Service
GetVariable () and GetNextVariableName () invocations.

The following are important points regarding the behavior of the
variable drivers when the variable runtime cache is enabled.

1. All of the non-volatile storage contents are loaded into the
   cache upon driver load. This one time load operation from storage
   is preferred as opposed to building the cache on demand. An on-
   demand cache would require a fallback SMI to load data into the
   cache as variables are requested.

2. SetVariable () requests will continue to always trigger an SMI.
   This occurs regardless of whether the variable is volatile or
   non-volatile.

3. Both volatile and non-volatile variables are cached in a runtime
   buffer. As is the case in the current EDK II variable driver, they
   continue to be cached in separate buffers.

4. The cache in Runtime DXE and SMM are intended to be exact copies
   of one another. All SMM variable accesses only return data from the
   SMM cache. The runtime caches are only updated after the variable I/O
   operation is successful in SMM. The runtime caches are only updated
   from SMM.

5. Synchronization mechanisms are in place to ensure the runtime cache
   content integrity with the SMM cache. These may result in updates to
   runtime cache that are the same in content but different in offset and
   size from updates to the SMM cache.

When using SMM variables with runtime cache enabled, two caches will now
be present.
1. "Runtime Cache" - Maintained in VariableSmmRuntimeDxe. Used to service
   Runtime Services GetVariable () and GetNextVariableName () callers.
2. "SMM Cache" - Maintained in VariableSmm to service SMM GetVariable ()
   and GetNextVariableName () callers.
   a. This cache is retained so SMM modules do not operate on data outside
      SMRAM.

Because a race condition can occur if an SMI occurs during the execution
of runtime code reading from the runtime cache, a runtime cache read lock
is introduced that explicitly moves pending updates from SMM to the runtime
cache if an SMM update occurs while the runtime cache is locked. Note that
it is not expected a Runtime services call will interrupt SMM processing
since all CPU cores rendezvous in SMM.

It is possible to view UEFI variable read and write statistics by setting
the gEfiMdeModulePkgTokenSpaceGuid.PcdVariableCollectStatistics FeaturePcd
to TRUE and using the VariableInfo UEFI application in MdeModulePkg to dump
variable statistics to the console. By doing so, a user can view the number
of GetVariable () hits from the Runtime DXE variable driver (Runtime Cache
hits) and the SMM variable driver (SMM Cache hits). SMM Cache hits for
GetVariable () will occur when SMM modules invoke GetVariable ().

Cc: Dandan Bi <dandan.bi@intel.com>
Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Eric Dong <eric.dong@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Cc: Liming Gao <liming.gao@intel.com>
Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Hao A Wu <hao.a.wu@intel.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Signed-off-by: Michael Kubacki <michael.a.kubacki@intel.com>
---
 MdeModulePkg/MdeModulePkg.dec                                        |  12 +
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf    |   2 +
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf           |   2 +
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf |  18 +-
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf  |   2 +
 MdeModulePkg/Include/Guid/SmmVariableCommon.h                        |  29 +-
 MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h                |  32 +-
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.h    |  51 ++
 MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c                |  50 +-
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.c    | 153 ++++++
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c             | 189 +++++++-
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c   | 512 +++++++++++++++++++-
 12 files changed, 1011 insertions(+), 41 deletions(-)

diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec
index d6bac974da..3ef8fe7644 100644
--- a/MdeModulePkg/MdeModulePkg.dec
+++ b/MdeModulePkg/MdeModulePkg.dec
@@ -641,6 +641,18 @@
   # @Prompt Enable Device Path From Text support.
   gEfiMdeModulePkgTokenSpaceGuid.PcdDevicePathSupportDevicePathFromText|TRUE|BOOLEAN|0x00010038
 
+  ## Indicates if the UEFI variable runtime cache should be enabled.
+  #  This setting only applies if SMM variables are enabled. When enabled, all variable
+  #  data for Runtime Service GetVariable () and GetNextVariableName () calls is retrieved
+  #  from a runtime data buffer referred to as the "runtime cache". An SMI is not triggered
+  #  at all for these requests. Variables writes still trigger an SMI. This can greatly
+  #  reduce overall system SMM usage as most boots tend to issue far more variable reads
+  #  than writes.<BR><BR>
+  #   TRUE  - The UEFI variable runtime cache is enabled.<BR>
+  #   FALSE - The UEFI variable runtime cache is disabled.<BR>
+  # @Prompt Enable the UEFI variable runtime cache.
+  gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE|BOOLEAN|0x00010039
+
   ## Indicates if the statistics about variable usage will be collected. This information is
   #  stored as a vendor configuration table into the EFI system table.
   #  Set this PCD to TRUE to use VariableInfo application in MdeModulePkg\Application directory to get
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
index 08a5490787..ceea5d1ff9 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
@@ -40,6 +40,8 @@
   VariableNonVolatile.h
   VariableParsing.c
   VariableParsing.h
+  VariableRuntimeCache.c
+  VariableRuntimeCache.h
   PrivilegePolymorphic.h
   Measurement.c
   TcgMorLockDxe.c
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf
index 6dc2721b81..bc3033588d 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf
@@ -49,6 +49,8 @@
   VariableNonVolatile.h
   VariableParsing.c
   VariableParsing.h
+  VariableRuntimeCache.c
+  VariableRuntimeCache.h
   VarCheck.c
   Variable.h
   PrivilegePolymorphic.h
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf
index 14894e6f13..a250533a53 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf
@@ -13,7 +13,7 @@
 #  may not be modified without authorization. If platform fails to protect these resources,
 #  the authentication service provided in this driver will be broken, and the behavior is undefined.
 #
-# Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2010 - 2019, Intel Corporation. All rights reserved.<BR>
 # SPDX-License-Identifier: BSD-2-Clause-Patent
 #
 ##
@@ -39,6 +39,8 @@
   VariableSmmRuntimeDxe.c
   PrivilegePolymorphic.h
   Measurement.c
+  VariableParsing.c
+  VariableParsing.h
 
 [Packages]
   MdePkg/MdePkg.dec
@@ -65,7 +67,21 @@
   gEdkiiVariableLockProtocolGuid                ## PRODUCES
   gEdkiiVarCheckProtocolGuid                    ## PRODUCES
 
+[FeaturePcd]
+  gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache           ## CONSUMES
+  gEfiMdeModulePkgTokenSpaceGuid.PcdVariableCollectStatistics            ## CONSUMES
+
 [Guids]
+  ## PRODUCES             ## GUID # Signature of Variable store header
+  ## CONSUMES             ## GUID # Signature of Variable store header
+  ## SOMETIMES_PRODUCES   ## SystemTable
+  gEfiAuthenticatedVariableGuid
+
+  ## PRODUCES             ## GUID # Signature of Variable store header
+  ## CONSUMES             ## GUID # Signature of Variable store header
+  ## SOMETIMES_PRODUCES   ## SystemTable
+  gEfiVariableGuid
+
   gEfiEventVirtualAddressChangeGuid             ## CONSUMES ## Event
   gEfiEventExitBootServicesGuid                 ## CONSUMES ## Event
   ## CONSUMES ## GUID # Locate protocol
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf
index f8a3742959..6e17f6cdf5 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf
@@ -49,6 +49,8 @@
   VariableNonVolatile.h
   VariableParsing.c
   VariableParsing.h
+  VariableRuntimeCache.c
+  VariableRuntimeCache.h
   VarCheck.c
   Variable.h
   PrivilegePolymorphic.h
diff --git a/MdeModulePkg/Include/Guid/SmmVariableCommon.h b/MdeModulePkg/Include/Guid/SmmVariableCommon.h
index c527a59891..ceef44dfd2 100644
--- a/MdeModulePkg/Include/Guid/SmmVariableCommon.h
+++ b/MdeModulePkg/Include/Guid/SmmVariableCommon.h
@@ -1,7 +1,7 @@
 /** @file
   The file defined some common structures used for communicating between SMM variable module and SMM variable wrapper module.
 
-Copyright (c) 2011 - 2015, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2011 - 2019, Intel Corporation. All rights reserved.<BR>
 SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
@@ -9,6 +9,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #ifndef _SMM_VARIABLE_COMMON_H_
 #define _SMM_VARIABLE_COMMON_H_
 
+#include <Guid/VariableFormat.h>
 #include <Protocol/VarCheck.h>
 
 #define EFI_SMM_VARIABLE_WRITE_GUID \
@@ -66,6 +67,16 @@ typedef struct {
 #define SMM_VARIABLE_FUNCTION_VAR_CHECK_VARIABLE_PROPERTY_GET  10
 
 #define SMM_VARIABLE_FUNCTION_GET_PAYLOAD_SIZE        11
+//
+// The payload for this function is SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT
+//
+#define SMM_VARIABLE_FUNCTION_INIT_RUNTIME_VARIABLE_CACHE_CONTEXT   12
+
+#define SMM_VARIABLE_FUNCTION_SYNC_RUNTIME_CACHE                    13
+//
+// The payload for this function is SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO
+//
+#define SMM_VARIABLE_FUNCTION_GET_RUNTIME_CACHE_INFO                14
 
 ///
 /// Size of SMM communicate header, without including the payload.
@@ -120,4 +131,20 @@ typedef struct {
   UINTN                         VariablePayloadSize;
 } SMM_VARIABLE_COMMUNICATE_GET_PAYLOAD_SIZE;
 
+typedef struct {
+  BOOLEAN                 *ReadLock;
+  BOOLEAN                 *PendingUpdate;
+  BOOLEAN                 *HobFlushComplete;
+  VARIABLE_STORE_HEADER   *RuntimeHobCache;
+  VARIABLE_STORE_HEADER   *RuntimeNvCache;
+  VARIABLE_STORE_HEADER   *RuntimeVolatileCache;
+} SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT;
+
+typedef struct {
+  UINTN                   TotalHobStorageSize;
+  UINTN                   TotalNvStorageSize;
+  UINTN                   TotalVolatileStorageSize;
+  BOOLEAN                 AuthenticatedVariableUsage;
+} SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO;
+
 #endif // _SMM_VARIABLE_COMMON_H_
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h
index fb574b2e32..0b2bb6ae66 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h
@@ -64,6 +64,21 @@ typedef enum {
   VariableStoreTypeMax
 } VARIABLE_STORE_TYPE;
 
+typedef struct {
+  UINT32                  PendingUpdateOffset;
+  UINT32                  PendingUpdateLength;
+  VARIABLE_STORE_HEADER   *Store;
+} VARIABLE_RUNTIME_CACHE;
+
+typedef struct {
+  BOOLEAN                 *ReadLock;
+  BOOLEAN                 *PendingUpdate;
+  BOOLEAN                 *HobFlushComplete;
+  VARIABLE_RUNTIME_CACHE  VariableRuntimeHobCache;
+  VARIABLE_RUNTIME_CACHE  VariableRuntimeNvCache;
+  VARIABLE_RUNTIME_CACHE  VariableRuntimeVolatileCache;
+} VARIABLE_RUNTIME_CACHE_CONTEXT;
+
 typedef struct {
   VARIABLE_HEADER *CurrPtr;
   //
@@ -79,14 +94,15 @@ typedef struct {
 } VARIABLE_POINTER_TRACK;
 
 typedef struct {
-  EFI_PHYSICAL_ADDRESS  HobVariableBase;
-  EFI_PHYSICAL_ADDRESS  VolatileVariableBase;
-  EFI_PHYSICAL_ADDRESS  NonVolatileVariableBase;
-  EFI_LOCK              VariableServicesLock;
-  UINT32                ReentrantState;
-  BOOLEAN               AuthFormat;
-  BOOLEAN               AuthSupport;
-  BOOLEAN               EmuNvMode;
+  EFI_PHYSICAL_ADDRESS            HobVariableBase;
+  EFI_PHYSICAL_ADDRESS            VolatileVariableBase;
+  EFI_PHYSICAL_ADDRESS            NonVolatileVariableBase;
+  VARIABLE_RUNTIME_CACHE_CONTEXT  VariableRuntimeCacheContext;
+  EFI_LOCK                        VariableServicesLock;
+  UINT32                          ReentrantState;
+  BOOLEAN                         AuthFormat;
+  BOOLEAN                         AuthSupport;
+  BOOLEAN                         EmuNvMode;
 } VARIABLE_GLOBAL;
 
 typedef struct {
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.h
new file mode 100644
index 0000000000..f9804a1d69
--- /dev/null
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.h
@@ -0,0 +1,51 @@
+/** @file
+  The common variable volatile store routines shared by the DXE_RUNTIME variable
+  module and the DXE_SMM variable module.
+
+Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef _VARIABLE_RUNTIME_CACHE_H_
+#define _VARIABLE_RUNTIME_CACHE_H_
+
+#include "Variable.h"
+
+/**
+  Copies any pending updates to runtime variable caches.
+
+  @retval EFI_UNSUPPORTED         The volatile store to be updated is not initialized properly.
+  @retval EFI_SUCCESS             The volatile store was updated successfully.
+
+**/
+EFI_STATUS
+FlushPendingRuntimeVariableCacheUpdates (
+  VOID
+  );
+
+/**
+  Synchronizes the runtime variable caches with all pending updates outside runtime.
+
+  Ensures all conditions are met to maintain coherency for runtime cache updates. This function will attempt
+  to write the given update (and any other pending updates) if the ReadLock is available. Otherwise, the
+  update is added as a pending update for the given variable store and it will be flushed to the runtime cache
+  at the next opportunity the ReadLock is available.
+
+  @param[in] VariableRuntimeCache Variable runtime cache structure for the runtime cache being synchronized.
+  @param[in] Offset               Offset in bytes to apply the update.
+  @param[in] Length               Length of data in bytes of the update.
+
+  @retval EFI_SUCCESS             The update was added as a pending update successfully. If the variable runtime
+                                  cache ReadLock was available, the runtime cache was updated successfully.
+  @retval EFI_UNSUPPORTED         The volatile store to be updated is not initialized properly.
+
+**/
+EFI_STATUS
+SynchronizeRuntimeVariableCache (
+  IN  VARIABLE_RUNTIME_CACHE          *VariableRuntimeCache,
+  IN  UINTN                           Offset,
+  IN  UINTN                           Length
+  );
+
+#endif
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
index 0bd2f22e1a..29d6aca993 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
@@ -25,6 +25,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #include "Variable.h"
 #include "VariableNonVolatile.h"
 #include "VariableParsing.h"
+#include "VariableRuntimeCache.h"
 
 VARIABLE_MODULE_GLOBAL  *mVariableModuleGlobal;
 
@@ -332,6 +333,12 @@ RecordVarErrorFlag (
       // Update the data in NV cache.
       //
       *VarErrFlag = TempFlag;
+      Status =  SynchronizeRuntimeVariableCache (
+                  &mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeNvCache,
+                  (UINTN) VarErrFlag - (UINTN) mNvVariableCache + (UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
+                  sizeof (TempFlag)
+                  );
+      ASSERT_EFI_ERROR (Status);
     }
   }
 }
@@ -766,12 +773,24 @@ Reclaim (
 
 Done:
   if (IsVolatile || mVariableModuleGlobal->VariableGlobal.EmuNvMode) {
+    Status =  SynchronizeRuntimeVariableCache (
+                &mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeVolatileCache,
+                0,
+                VariableStoreHeader->Size
+                );
+    ASSERT_EFI_ERROR (Status);
     FreePool (ValidBuffer);
   } else {
     //
     // For NV variable reclaim, we use mNvVariableCache as the buffer, so copy the data back.
     //
-    CopyMem (mNvVariableCache, (UINT8 *)(UINTN)VariableBase, VariableStoreHeader->Size);
+    CopyMem (mNvVariableCache, (UINT8 *) (UINTN) VariableBase, VariableStoreHeader->Size);
+    Status =  SynchronizeRuntimeVariableCache (
+                &mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeNvCache,
+                0,
+                VariableStoreHeader->Size
+                );
+    ASSERT_EFI_ERROR (Status);
   }
 
   return Status;
@@ -1614,6 +1633,7 @@ UpdateVariable (
   VARIABLE_POINTER_TRACK              *Variable;
   VARIABLE_POINTER_TRACK              NvVariable;
   VARIABLE_STORE_HEADER               *VariableStoreHeader;
+  VARIABLE_RUNTIME_CACHE              *VolatileCacheInstance;
   UINT8                               *BufferForMerge;
   UINTN                               MergedBufSize;
   BOOLEAN                             DataReady;
@@ -2275,6 +2295,23 @@ UpdateVariable (
   }
 
 Done:
+  if (!EFI_ERROR (Status)) {
+    if (Variable->Volatile) {
+      VolatileCacheInstance = &(mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeVolatileCache);
+    } else {
+      VolatileCacheInstance = &(mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeNvCache);
+    }
+
+    if (VolatileCacheInstance->Store != NULL) {
+      Status =  SynchronizeRuntimeVariableCache (
+                  VolatileCacheInstance,
+                  0,
+                  VolatileCacheInstance->Store->Size
+                  );
+      ASSERT_EFI_ERROR (Status);
+    }
+  }
+
   return Status;
 }
 
@@ -3200,6 +3237,14 @@ FlushHobVariableToFlash (
         ErrorFlag = TRUE;
       }
     }
+    if (mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeHobCache.Store != NULL) {
+      Status =  SynchronizeRuntimeVariableCache (
+                  &mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeHobCache,
+                  0,
+                  mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeHobCache.Store->Size
+                  );
+      ASSERT_EFI_ERROR (Status);
+    }
     if (ErrorFlag) {
       //
       // We still have HOB variable(s) not flushed in flash.
@@ -3210,6 +3255,9 @@ FlushHobVariableToFlash (
       // All HOB variables have been flushed in flash.
       //
       DEBUG ((EFI_D_INFO, "Variable driver: all HOB variables have been flushed in flash.\n"));
+      if (mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.HobFlushComplete != NULL) {
+        *(mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.HobFlushComplete) = TRUE;
+      }
       if (!AtRuntime ()) {
         FreePool ((VOID *) VariableStoreHeader);
       }
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.c
new file mode 100644
index 0000000000..bc93cc07d2
--- /dev/null
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.c
@@ -0,0 +1,153 @@
+/** @file
+  Functions related to managing the UEFI variable runtime cache. This file should only include functions
+  used by the SMM UEFI variable driver.
+
+  Caution: This module requires additional review when modified.
+  This driver will have external input - variable data. They may be input in SMM mode.
+  This external input must be validated carefully to avoid security issue like
+  buffer overflow, integer overflow.
+
+Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "VariableParsing.h"
+#include "VariableRuntimeCache.h"
+
+extern VARIABLE_MODULE_GLOBAL   *mVariableModuleGlobal;
+extern VARIABLE_STORE_HEADER    *mNvVariableCache;
+
+/**
+  Copies any pending updates to runtime variable caches.
+
+  @retval EFI_UNSUPPORTED         The volatile store to be updated is not initialized properly.
+  @retval EFI_SUCCESS             The volatile store was updated successfully.
+
+**/
+EFI_STATUS
+FlushPendingRuntimeVariableCacheUpdates (
+  VOID
+  )
+{
+  VARIABLE_RUNTIME_CACHE_CONTEXT    *VariableRuntimeCacheContext;
+
+  VariableRuntimeCacheContext = &mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext;
+
+  if (VariableRuntimeCacheContext->VariableRuntimeNvCache.Store == NULL ||
+      VariableRuntimeCacheContext->VariableRuntimeVolatileCache.Store == NULL ||
+      VariableRuntimeCacheContext->PendingUpdate == NULL) {
+    return EFI_UNSUPPORTED;
+  }
+
+  if (*(VariableRuntimeCacheContext->PendingUpdate)) {
+    if (VariableRuntimeCacheContext->VariableRuntimeHobCache.Store != NULL &&
+        mVariableModuleGlobal->VariableGlobal.HobVariableBase > 0) {
+      CopyMem (
+        (VOID *) (
+          ((UINT8 *) (UINTN) VariableRuntimeCacheContext->VariableRuntimeHobCache.Store) +
+          VariableRuntimeCacheContext->VariableRuntimeHobCache.PendingUpdateOffset
+          ),
+        (VOID *) (
+          ((UINT8 *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase) +
+          VariableRuntimeCacheContext->VariableRuntimeHobCache.PendingUpdateOffset
+          ),
+        VariableRuntimeCacheContext->VariableRuntimeHobCache.PendingUpdateLength
+        );
+      VariableRuntimeCacheContext->VariableRuntimeHobCache.PendingUpdateLength = 0;
+      VariableRuntimeCacheContext->VariableRuntimeHobCache.PendingUpdateOffset = 0;
+    }
+
+    CopyMem (
+      (VOID *) (
+        ((UINT8 *) (UINTN) VariableRuntimeCacheContext->VariableRuntimeNvCache.Store) +
+        VariableRuntimeCacheContext->VariableRuntimeNvCache.PendingUpdateOffset
+        ),
+      (VOID *) (
+        ((UINT8 *) (UINTN) mNvVariableCache) +
+        VariableRuntimeCacheContext->VariableRuntimeNvCache.PendingUpdateOffset
+        ),
+      VariableRuntimeCacheContext->VariableRuntimeNvCache.PendingUpdateLength
+      );
+    VariableRuntimeCacheContext->VariableRuntimeNvCache.PendingUpdateLength = 0;
+    VariableRuntimeCacheContext->VariableRuntimeNvCache.PendingUpdateOffset = 0;
+
+    CopyMem (
+      (VOID *) (
+        ((UINT8 *) (UINTN) VariableRuntimeCacheContext->VariableRuntimeVolatileCache.Store) +
+        VariableRuntimeCacheContext->VariableRuntimeVolatileCache.PendingUpdateOffset
+      ),
+      (VOID *) (
+        ((UINT8 *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase) +
+        VariableRuntimeCacheContext->VariableRuntimeVolatileCache.PendingUpdateOffset
+        ),
+      VariableRuntimeCacheContext->VariableRuntimeVolatileCache.PendingUpdateLength
+      );
+    VariableRuntimeCacheContext->VariableRuntimeVolatileCache.PendingUpdateLength = 0;
+    VariableRuntimeCacheContext->VariableRuntimeVolatileCache.PendingUpdateOffset = 0;
+    *(VariableRuntimeCacheContext->PendingUpdate) = FALSE;
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Synchronizes the runtime variable caches with all pending updates outside runtime.
+
+  Ensures all conditions are met to maintain coherency for runtime cache updates. This function will attempt
+  to write the given update (and any other pending updates) if the ReadLock is available. Otherwise, the
+  update is added as a pending update for the given variable store and it will be flushed to the runtime cache
+  at the next opportunity the ReadLock is available.
+
+  @param[in] VariableRuntimeCache Variable runtime cache structure for the runtime cache being synchronized.
+  @param[in] Offset               Offset in bytes to apply the update.
+  @param[in] Length               Length of data in bytes of the update.
+
+  @retval EFI_SUCCESS             The update was added as a pending update successfully. If the variable runtime
+                                  cache ReadLock was available, the runtime cache was updated successfully.
+  @retval EFI_UNSUPPORTED         The volatile store to be updated is not initialized properly.
+
+**/
+EFI_STATUS
+SynchronizeRuntimeVariableCache (
+  IN  VARIABLE_RUNTIME_CACHE          *VariableRuntimeCache,
+  IN  UINTN                           Offset,
+  IN  UINTN                           Length
+  )
+{
+  if (VariableRuntimeCache == NULL) {
+    return EFI_INVALID_PARAMETER;
+  } else if (VariableRuntimeCache->Store == NULL) {
+    // The runtime cache may not be active or allocated yet.
+    // In either case, return EFI_SUCCESS instead of EFI_NOT_AVAILABLE_YET.
+    return EFI_SUCCESS;
+  }
+
+  if (mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.PendingUpdate == NULL ||
+      mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.ReadLock == NULL) {
+    return EFI_UNSUPPORTED;
+  }
+
+  if (*(mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.PendingUpdate) &&
+      VariableRuntimeCache->PendingUpdateLength > 0) {
+    VariableRuntimeCache->PendingUpdateLength =
+      (UINT32) (
+        MAX (
+          (UINTN) (VariableRuntimeCache->PendingUpdateOffset + VariableRuntimeCache->PendingUpdateLength),
+          Offset + Length
+        ) - MIN ((UINTN) VariableRuntimeCache->PendingUpdateOffset, Offset)
+      );
+    VariableRuntimeCache->PendingUpdateOffset =
+      (UINT32) MIN ((UINTN) VariableRuntimeCache->PendingUpdateOffset, Offset);
+  } else {
+    VariableRuntimeCache->PendingUpdateLength = (UINT32) Length;
+    VariableRuntimeCache->PendingUpdateOffset = (UINT32) Offset;
+  }
+  *(mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.PendingUpdate) = TRUE;
+
+  if (*(mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.ReadLock) == FALSE) {
+    return FlushPendingRuntimeVariableCacheUpdates ();
+  }
+
+  return EFI_SUCCESS;
+}
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c
index 5e24bc4a62..caca5c3241 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c
@@ -31,6 +31,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #include <Guid/SmmVariableCommon.h>
 #include "Variable.h"
 #include "VariableParsing.h"
+#include "VariableRuntimeCache.h"
+
+extern VARIABLE_STORE_HEADER                         *mNvVariableCache;
 
 BOOLEAN                                              mAtRuntime              = FALSE;
 UINT8                                                *mVariableBufferPayload = NULL;
@@ -451,25 +454,29 @@ SmmVariableGetStatistics (
 EFI_STATUS
 EFIAPI
 SmmVariableHandler (
-  IN     EFI_HANDLE                                DispatchHandle,
-  IN     CONST VOID                                *RegisterContext,
-  IN OUT VOID                                      *CommBuffer,
-  IN OUT UINTN                                     *CommBufferSize
+  IN     EFI_HANDLE                                       DispatchHandle,
+  IN     CONST VOID                                       *RegisterContext,
+  IN OUT VOID                                             *CommBuffer,
+  IN OUT UINTN                                            *CommBufferSize
   )
 {
-  EFI_STATUS                                       Status;
-  SMM_VARIABLE_COMMUNICATE_HEADER                  *SmmVariableFunctionHeader;
-  SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE         *SmmVariableHeader;
-  SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME  *GetNextVariableName;
-  SMM_VARIABLE_COMMUNICATE_QUERY_VARIABLE_INFO     *QueryVariableInfo;
-  SMM_VARIABLE_COMMUNICATE_GET_PAYLOAD_SIZE        *GetPayloadSize;
-  VARIABLE_INFO_ENTRY                              *VariableInfo;
-  SMM_VARIABLE_COMMUNICATE_LOCK_VARIABLE           *VariableToLock;
-  SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY *CommVariableProperty;
-  UINTN                                            InfoSize;
-  UINTN                                            NameBufferSize;
-  UINTN                                            CommBufferPayloadSize;
-  UINTN                                            TempCommBufferSize;
+  EFI_STATUS                                              Status;
+  SMM_VARIABLE_COMMUNICATE_HEADER                         *SmmVariableFunctionHeader;
+  SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE                *SmmVariableHeader;
+  SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME         *GetNextVariableName;
+  SMM_VARIABLE_COMMUNICATE_QUERY_VARIABLE_INFO            *QueryVariableInfo;
+  SMM_VARIABLE_COMMUNICATE_GET_PAYLOAD_SIZE               *GetPayloadSize;
+  SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT *RuntimeVariableCacheContext;
+  SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO         *GetRuntimeCacheInfo;
+  SMM_VARIABLE_COMMUNICATE_LOCK_VARIABLE                  *VariableToLock;
+  SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY    *CommVariableProperty;
+  VARIABLE_INFO_ENTRY                                     *VariableInfo;
+  VARIABLE_RUNTIME_CACHE_CONTEXT                          *VariableCacheContext;
+  VARIABLE_STORE_HEADER                                   *VariableCache;
+  UINTN                                                   InfoSize;
+  UINTN                                                   NameBufferSize;
+  UINTN                                                   CommBufferPayloadSize;
+  UINTN                                                   TempCommBufferSize;
 
   //
   // If input is invalid, stop processing this SMI
@@ -789,6 +796,154 @@ SmmVariableHandler (
                  );
       CopyMem (SmmVariableFunctionHeader->Data, mVariableBufferPayload, CommBufferPayloadSize);
       break;
+    case SMM_VARIABLE_FUNCTION_INIT_RUNTIME_VARIABLE_CACHE_CONTEXT:
+      if (CommBufferPayloadSize < sizeof (SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT)) {
+        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: SMM communication buffer size invalid!\n"));
+        Status = EFI_ACCESS_DENIED;
+        goto EXIT;
+      }
+      if (mEndOfDxe) {
+        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Cannot init context after end of DXE!\n"));
+        Status = EFI_ACCESS_DENIED;
+        goto EXIT;
+      }
+
+      //
+      // Copy the input communicate buffer payload to the pre-allocated SMM variable payload buffer.
+      //
+      CopyMem (mVariableBufferPayload, SmmVariableFunctionHeader->Data, CommBufferPayloadSize);
+      RuntimeVariableCacheContext = (SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT *) mVariableBufferPayload;
+
+      //
+      // Verify required runtime cache buffers are provided.
+      //
+      if (RuntimeVariableCacheContext->RuntimeVolatileCache == NULL ||
+          RuntimeVariableCacheContext->RuntimeNvCache == NULL ||
+          RuntimeVariableCacheContext->PendingUpdate == NULL ||
+          RuntimeVariableCacheContext->ReadLock == NULL ||
+          RuntimeVariableCacheContext->HobFlushComplete == NULL) {
+        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Required runtime cache buffer is NULL!\n"));
+        Status = EFI_ACCESS_DENIED;
+        goto EXIT;
+      }
+
+      //
+      // Verify minimum size requirements for the runtime variable store buffers.
+      //
+      if ((RuntimeVariableCacheContext->RuntimeHobCache != NULL &&
+          RuntimeVariableCacheContext->RuntimeHobCache->Size < sizeof (VARIABLE_STORE_HEADER)) ||
+          RuntimeVariableCacheContext->RuntimeVolatileCache->Size < sizeof (VARIABLE_STORE_HEADER) ||
+          RuntimeVariableCacheContext->RuntimeNvCache->Size < sizeof (VARIABLE_STORE_HEADER)) {
+        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: A runtime cache buffer size is invalid!\n"));
+        Status = EFI_ACCESS_DENIED;
+        goto EXIT;
+      }
+
+      //
+      // Verify runtime buffers do not overlap with SMRAM ranges.
+      //
+      if (RuntimeVariableCacheContext->RuntimeHobCache != NULL &&
+          !VariableSmmIsBufferOutsideSmmValid (
+            (UINTN) RuntimeVariableCacheContext->RuntimeHobCache,
+            (UINTN) RuntimeVariableCacheContext->RuntimeHobCache->Size)) {
+        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Runtime HOB cache buffer in SMRAM or overflow!\n"));
+        Status = EFI_ACCESS_DENIED;
+        goto EXIT;
+      }
+      if (!VariableSmmIsBufferOutsideSmmValid (
+            (UINTN) RuntimeVariableCacheContext->RuntimeVolatileCache,
+            (UINTN) RuntimeVariableCacheContext->RuntimeVolatileCache->Size)) {
+        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Runtime volatile cache buffer in SMRAM or overflow!\n"));
+        Status = EFI_ACCESS_DENIED;
+        goto EXIT;
+      }
+      if (!VariableSmmIsBufferOutsideSmmValid (
+            (UINTN) RuntimeVariableCacheContext->RuntimeNvCache,
+            (UINTN) RuntimeVariableCacheContext->RuntimeNvCache->Size)) {
+        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Runtime non-volatile cache buffer in SMRAM or overflow!\n"));
+        Status = EFI_ACCESS_DENIED;
+        goto EXIT;
+      }
+      if (!VariableSmmIsBufferOutsideSmmValid (
+            (UINTN) RuntimeVariableCacheContext->PendingUpdate,
+            sizeof (*(RuntimeVariableCacheContext->PendingUpdate)))) {
+        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Runtime cache pending update buffer in SMRAM or overflow!\n"));
+        Status = EFI_ACCESS_DENIED;
+        goto EXIT;
+      }
+      if (!VariableSmmIsBufferOutsideSmmValid (
+            (UINTN) RuntimeVariableCacheContext->ReadLock,
+            sizeof (*(RuntimeVariableCacheContext->ReadLock)))) {
+        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Runtime cache read lock buffer in SMRAM or overflow!\n"));
+        Status = EFI_ACCESS_DENIED;
+        goto EXIT;
+      }
+      if (!VariableSmmIsBufferOutsideSmmValid (
+            (UINTN) RuntimeVariableCacheContext->HobFlushComplete,
+            sizeof (*(RuntimeVariableCacheContext->HobFlushComplete)))) {
+        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Runtime cache HOB flush complete buffer in SMRAM or overflow!\n"));
+        Status = EFI_ACCESS_DENIED;
+        goto EXIT;
+      }
+
+      VariableCacheContext = &mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext;
+      VariableCacheContext->VariableRuntimeHobCache.Store      = RuntimeVariableCacheContext->RuntimeHobCache;
+      VariableCacheContext->VariableRuntimeVolatileCache.Store = RuntimeVariableCacheContext->RuntimeVolatileCache;
+      VariableCacheContext->VariableRuntimeNvCache.Store       = RuntimeVariableCacheContext->RuntimeNvCache;
+      VariableCacheContext->PendingUpdate                      = RuntimeVariableCacheContext->PendingUpdate;
+      VariableCacheContext->ReadLock                           = RuntimeVariableCacheContext->ReadLock;
+      VariableCacheContext->HobFlushComplete                   = RuntimeVariableCacheContext->HobFlushComplete;
+
+      // Set up the intial pending request since the RT cache needs to be in sync with SMM cache
+      VariableCacheContext->VariableRuntimeHobCache.PendingUpdateOffset = 0;
+      VariableCacheContext->VariableRuntimeHobCache.PendingUpdateLength = 0;
+      if (mVariableModuleGlobal->VariableGlobal.HobVariableBase > 0 &&
+          VariableCacheContext->VariableRuntimeHobCache.Store != NULL) {
+        VariableCache = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
+        VariableCacheContext->VariableRuntimeHobCache.PendingUpdateLength = (UINT32) ((UINTN) GetEndPointer (VariableCache) - (UINTN) VariableCache);
+        CopyGuid (&(VariableCacheContext->VariableRuntimeHobCache.Store->Signature), &(VariableCache->Signature));
+      }
+      VariableCache = (VARIABLE_STORE_HEADER  *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
+      VariableCacheContext->VariableRuntimeVolatileCache.PendingUpdateOffset   = 0;
+      VariableCacheContext->VariableRuntimeVolatileCache.PendingUpdateLength   = (UINT32) ((UINTN) GetEndPointer (VariableCache) - (UINTN) VariableCache);
+      CopyGuid (&(VariableCacheContext->VariableRuntimeVolatileCache.Store->Signature), &(VariableCache->Signature));
+
+      VariableCache = (VARIABLE_STORE_HEADER  *) (UINTN) mNvVariableCache;
+      VariableCacheContext->VariableRuntimeNvCache.PendingUpdateOffset = 0;
+      VariableCacheContext->VariableRuntimeNvCache.PendingUpdateLength = (UINT32) ((UINTN) GetEndPointer (VariableCache) - (UINTN) VariableCache);
+      CopyGuid (&(VariableCacheContext->VariableRuntimeNvCache.Store->Signature), &(VariableCache->Signature));
+
+      *(VariableCacheContext->PendingUpdate) = TRUE;
+      *(VariableCacheContext->ReadLock) = FALSE;
+      *(VariableCacheContext->HobFlushComplete) = FALSE;
+
+      Status = EFI_SUCCESS;
+      break;
+    case SMM_VARIABLE_FUNCTION_SYNC_RUNTIME_CACHE:
+      Status = FlushPendingRuntimeVariableCacheUpdates ();
+      break;
+    case SMM_VARIABLE_FUNCTION_GET_RUNTIME_CACHE_INFO:
+      if (CommBufferPayloadSize < sizeof (SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO)) {
+        DEBUG ((DEBUG_ERROR, "GetRuntimeCacheInfo: SMM communication buffer size invalid!\n"));
+        return EFI_SUCCESS;
+      }
+      GetRuntimeCacheInfo = (SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO *) SmmVariableFunctionHeader->Data;
+
+      if (mVariableModuleGlobal->VariableGlobal.HobVariableBase > 0) {
+        VariableCache = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;
+        GetRuntimeCacheInfo->TotalHobStorageSize = VariableCache->Size;
+      } else {
+        GetRuntimeCacheInfo->TotalHobStorageSize = 0;
+      }
+
+      VariableCache = (VARIABLE_STORE_HEADER  *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
+      GetRuntimeCacheInfo->TotalVolatileStorageSize = VariableCache->Size;
+      VariableCache = (VARIABLE_STORE_HEADER  *) (UINTN) mNvVariableCache;
+      GetRuntimeCacheInfo->TotalNvStorageSize = (UINTN) VariableCache->Size;
+      GetRuntimeCacheInfo->AuthenticatedVariableUsage = mVariableModuleGlobal->VariableGlobal.AuthFormat;
+
+      Status = EFI_SUCCESS;
+      break;
 
     default:
       Status = EFI_UNSUPPORTED;
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c
index 0a1888e5ef..3dee05fded 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c
@@ -13,7 +13,7 @@
 
   InitCommunicateBuffer() is really function to check the variable data size.
 
-Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2010 - 2019, Intel Corporation. All rights reserved.<BR>
 SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
@@ -39,6 +39,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #include <Guid/SmmVariableCommon.h>
 
 #include "PrivilegePolymorphic.h"
+#include "VariableParsing.h"
 
 EFI_HANDLE                       mHandle                    = NULL;
 EFI_SMM_VARIABLE_PROTOCOL       *mSmmVariable               = NULL;
@@ -46,8 +47,19 @@ EFI_EVENT                        mVirtualAddressChangeEvent = NULL;
 EFI_SMM_COMMUNICATION_PROTOCOL  *mSmmCommunication          = NULL;
 UINT8                           *mVariableBuffer            = NULL;
 UINT8                           *mVariableBufferPhysical    = NULL;
+VARIABLE_INFO_ENTRY             *mVariableInfo              = NULL;
+VARIABLE_STORE_HEADER           *mVariableRuntimeHobCacheBuffer           = NULL;
+VARIABLE_STORE_HEADER           *mVariableRuntimeNvCacheBuffer            = NULL;
+VARIABLE_STORE_HEADER           *mVariableRuntimeVolatileCacheBuffer      = NULL;
 UINTN                            mVariableBufferSize;
+UINTN                            mVariableRuntimeHobCacheBufferSize;
+UINTN                            mVariableRuntimeNvCacheBufferSize;
+UINTN                            mVariableRuntimeVolatileCacheBufferSize;
 UINTN                            mVariableBufferPayloadSize;
+BOOLEAN                          mVariableRuntimeCachePendingUpdate;
+BOOLEAN                          mVariableRuntimeCacheReadLock;
+BOOLEAN                          mVariableAuthFormat;
+BOOLEAN                          mHobFlushComplete;
 EFI_LOCK                         mVariableServicesLock;
 EDKII_VARIABLE_LOCK_PROTOCOL     mVariableLock;
 EDKII_VAR_CHECK_PROTOCOL         mVarCheck;
@@ -107,6 +119,72 @@ ReleaseLockOnlyAtBootTime (
   }
 }
 
+/**
+  Return TRUE if ExitBootServices () has been called.
+
+  @retval TRUE If ExitBootServices () has been called. FALSE if ExitBootServices () has not been called.
+**/
+BOOLEAN
+AtRuntime (
+  VOID
+  )
+{
+  return EfiAtRuntime ();
+}
+
+/**
+  Initialize the variable cache buffer as an empty variable store.
+
+  @param[out]     VariableCacheBuffer     A pointer to pointer of a cache variable store.
+  @param[in,out]  TotalVariableCacheSize  On input, the minimum size needed for the UEFI variable store cache
+                                          buffer that is allocated. On output, the actual size of the buffer allocated.
+                                          If TotalVariableCacheSize is zero, a buffer will not be allocated and the
+                                          function will return with EFI_SUCCESS.
+
+  @retval EFI_SUCCESS             The variable cache was allocated and initialized successfully.
+  @retval EFI_INVALID_PARAMETER   A given pointer is NULL or an invalid variable store size was specified.
+  @retval EFI_OUT_OF_RESOURCES    Insufficient resources are available to allocate the variable store cache buffer.
+
+**/
+EFI_STATUS
+InitVariableCache (
+  OUT    VARIABLE_STORE_HEADER   **VariableCacheBuffer,
+  IN OUT UINTN                   *TotalVariableCacheSize
+  )
+{
+  VARIABLE_STORE_HEADER   *VariableCacheStorePtr;
+
+  if (TotalVariableCacheSize == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+  if (*TotalVariableCacheSize == 0) {
+    return EFI_SUCCESS;
+  }
+  if (VariableCacheBuffer == NULL || *TotalVariableCacheSize < sizeof (VARIABLE_STORE_HEADER)) {
+    return EFI_INVALID_PARAMETER;
+  }
+  *TotalVariableCacheSize = ALIGN_VALUE (*TotalVariableCacheSize, sizeof (UINT32));
+
+  //
+  // Allocate NV Storage Cache and initialize it to all 1's (like an erased FV)
+  //
+  *VariableCacheBuffer =  (VARIABLE_STORE_HEADER *) AllocateRuntimePages (
+                            EFI_SIZE_TO_PAGES (*TotalVariableCacheSize)
+                            );
+  if (*VariableCacheBuffer == NULL) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+  VariableCacheStorePtr = *VariableCacheBuffer;
+  SetMem32 ((VOID *) VariableCacheStorePtr, *TotalVariableCacheSize, (UINT32) 0xFFFFFFFF);
+
+  ZeroMem ((VOID *) VariableCacheStorePtr, sizeof (VARIABLE_STORE_HEADER));
+  VariableCacheStorePtr->Size    = (UINT32) *TotalVariableCacheSize;
+  VariableCacheStorePtr->Format  = VARIABLE_STORE_FORMATTED;
+  VariableCacheStorePtr->State   = VARIABLE_STORE_HEALTHY;
+
+  return EFI_SUCCESS;
+}
+
 /**
   Initialize the communicate buffer using DataSize and Function.
 
@@ -425,7 +503,169 @@ Done:
 }
 
 /**
-  This code finds variable in storage blocks (Volatile or Non-Volatile).
+  Signals SMM to synchronize any pending variable updates with the runtime cache(s).
+
+**/
+VOID
+SyncRuntimeCache (
+  VOID
+  )
+{
+  //
+  // Init the communicate buffer. The buffer data size is:
+  // SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE.
+  //
+  InitCommunicateBuffer (NULL, 0, SMM_VARIABLE_FUNCTION_SYNC_RUNTIME_CACHE);
+
+  //
+  // Send data to SMM.
+  //
+  SendCommunicateBuffer (0);
+}
+
+/**
+  Check whether a SMI must be triggered to retrieve pending cache updates.
+
+  If the variable HOB was finished being flushed since the last check for a runtime cache update, this function
+  will prevent the HOB cache from being used for future runtime cache hits.
+
+**/
+VOID
+CheckForRuntimeCacheSync (
+  VOID
+  )
+{
+  if (mVariableRuntimeCachePendingUpdate) {
+    SyncRuntimeCache ();
+  }
+  ASSERT (!mVariableRuntimeCachePendingUpdate);
+
+  //
+  // The HOB variable data may have finished being flushed in the runtime cache sync update
+  //
+  if (mHobFlushComplete && mVariableRuntimeHobCacheBuffer != NULL) {
+    if (!EfiAtRuntime ()) {
+      FreePages (mVariableRuntimeHobCacheBuffer, EFI_SIZE_TO_PAGES (mVariableRuntimeHobCacheBufferSize));
+    }
+    mVariableRuntimeHobCacheBuffer = NULL;
+  }
+}
+
+/**
+  Finds the given variable in a runtime cache variable store.
+
+  Caution: This function may receive untrusted input.
+  The data size is external input, so this function will validate it carefully to avoid buffer overflow.
+
+  @param[in]      VariableName       Name of Variable to be found.
+  @param[in]      VendorGuid         Variable vendor GUID.
+  @param[out]     Attributes         Attribute value of the variable found.
+  @param[in, out] DataSize           Size of Data found. If size is less than the
+                                     data, this value contains the required size.
+  @param[out]     Data               Data pointer.
+
+  @retval EFI_SUCCESS                Found the specified variable.
+  @retval EFI_INVALID_PARAMETER      Invalid parameter.
+  @retval EFI_NOT_FOUND              The specified variable could not be found.
+
+**/
+EFI_STATUS
+FindVariableInRuntimeCache (
+  IN      CHAR16                            *VariableName,
+  IN      EFI_GUID                          *VendorGuid,
+  OUT     UINT32                            *Attributes OPTIONAL,
+  IN OUT  UINTN                             *DataSize,
+  OUT     VOID                              *Data OPTIONAL
+  )
+{
+  EFI_STATUS              Status;
+  UINTN                   TempDataSize;
+  VARIABLE_POINTER_TRACK  RtPtrTrack;
+  VARIABLE_STORE_TYPE     StoreType;
+  VARIABLE_STORE_HEADER   *VariableStoreList[VariableStoreTypeMax];
+
+  Status = EFI_NOT_FOUND;
+
+  if (VariableName == NULL || VendorGuid == NULL || DataSize == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  //
+  // The UEFI specification restricts Runtime Services callers from invoking the same or certain other Runtime Service
+  // functions prior to completion and return from a previous Runtime Service call. These restrictions prevent
+  // a GetVariable () or GetNextVariable () call from being issued until a prior call has returned. The runtime
+  // cache read lock should always be free when entering this function.
+  //
+  ASSERT (!mVariableRuntimeCacheReadLock);
+
+  mVariableRuntimeCacheReadLock = TRUE;
+  CheckForRuntimeCacheSync ();
+
+  if (!mVariableRuntimeCachePendingUpdate) {
+    //
+    // 0: Volatile, 1: HOB, 2: Non-Volatile.
+    // The index and attributes mapping must be kept in this order as FindVariable
+    // makes use of this mapping to implement search algorithm.
+    //
+    VariableStoreList[VariableStoreTypeVolatile] = mVariableRuntimeVolatileCacheBuffer;
+    VariableStoreList[VariableStoreTypeHob]      = mVariableRuntimeHobCacheBuffer;
+    VariableStoreList[VariableStoreTypeNv]       = mVariableRuntimeNvCacheBuffer;
+
+    for (StoreType = (VARIABLE_STORE_TYPE) 0; StoreType < VariableStoreTypeMax; StoreType++) {
+      if (VariableStoreList[StoreType] == NULL) {
+        continue;
+      }
+
+      RtPtrTrack.StartPtr = GetStartPointer (VariableStoreList[StoreType]);
+      RtPtrTrack.EndPtr   = GetEndPointer   (VariableStoreList[StoreType]);
+      RtPtrTrack.Volatile = (BOOLEAN) (StoreType == VariableStoreTypeVolatile);
+
+      Status = FindVariableEx (VariableName, VendorGuid, FALSE, &RtPtrTrack, mVariableAuthFormat);
+      if (!EFI_ERROR (Status)) {
+        break;
+      }
+    }
+
+    if (!EFI_ERROR (Status)) {
+      //
+      // Get data size
+      //
+      TempDataSize = DataSizeOfVariable (RtPtrTrack.CurrPtr, mVariableAuthFormat);
+      ASSERT (TempDataSize != 0);
+
+      if (*DataSize >= TempDataSize) {
+        if (Data == NULL) {
+          Status = EFI_INVALID_PARAMETER;
+          goto Done;
+        }
+
+        CopyMem (Data, GetVariableDataPtr (RtPtrTrack.CurrPtr, mVariableAuthFormat), TempDataSize);
+        if (Attributes != NULL) {
+          *Attributes = RtPtrTrack.CurrPtr->Attributes;
+        }
+
+        *DataSize = TempDataSize;
+
+        UpdateVariableInfo (VariableName, VendorGuid, RtPtrTrack.Volatile, TRUE, FALSE, FALSE, TRUE, &mVariableInfo);
+
+        Status = EFI_SUCCESS;
+        goto Done;
+      } else {
+        *DataSize = TempDataSize;
+        Status = EFI_BUFFER_TOO_SMALL;
+        goto Done;
+      }
+    }
+  }
+
+Done:
+  mVariableRuntimeCacheReadLock = FALSE;
+
+  return Status;
+}
+
+/**
+  Finds the given variable in a variable store in SMM.
 
   Caution: This function may receive untrusted input.
   The data size is external input, so this function will validate it carefully to avoid buffer overflow.
@@ -437,20 +677,18 @@ Done:
                                      data, this value contains the required size.
   @param[out]     Data               Data pointer.
 
+  @retval EFI_SUCCESS                Found the specified variable.
   @retval EFI_INVALID_PARAMETER      Invalid parameter.
-  @retval EFI_SUCCESS                Find the specified variable.
-  @retval EFI_NOT_FOUND              Not found.
-  @retval EFI_BUFFER_TO_SMALL        DataSize is too small for the result.
+  @retval EFI_NOT_FOUND              The specified variable could not be found.
 
 **/
 EFI_STATUS
-EFIAPI
-RuntimeServiceGetVariable (
+FindVariableInSmm (
   IN      CHAR16                            *VariableName,
   IN      EFI_GUID                          *VendorGuid,
   OUT     UINT32                            *Attributes OPTIONAL,
   IN OUT  UINTN                             *DataSize,
-  OUT     VOID                              *Data
+  OUT     VOID                              *Data OPTIONAL
   )
 {
   EFI_STATUS                                Status;
@@ -474,8 +712,6 @@ RuntimeServiceGetVariable (
     return EFI_INVALID_PARAMETER;
   }
 
-  AcquireLockOnlyAtBootTime(&mVariableServicesLock);
-
   //
   // Init the communicate buffer. The buffer data size is:
   // SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + PayloadSize.
@@ -488,7 +724,7 @@ RuntimeServiceGetVariable (
   }
   PayloadSize = OFFSET_OF (SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name) + VariableNameSize + TempDataSize;
 
-  Status = InitCommunicateBuffer ((VOID **)&SmmVariableHeader, PayloadSize, SMM_VARIABLE_FUNCTION_GET_VARIABLE);
+  Status = InitCommunicateBuffer ((VOID **) &SmmVariableHeader, PayloadSize, SMM_VARIABLE_FUNCTION_GET_VARIABLE);
   if (EFI_ERROR (Status)) {
     goto Done;
   }
@@ -534,11 +770,58 @@ RuntimeServiceGetVariable (
   }
 
 Done:
+  return Status;
+}
+
+/**
+  This code finds variable in storage blocks (Volatile or Non-Volatile).
+
+  Caution: This function may receive untrusted input.
+  The data size is external input, so this function will validate it carefully to avoid buffer overflow.
+
+  @param[in]      VariableName       Name of Variable to be found.
+  @param[in]      VendorGuid         Variable vendor GUID.
+  @param[out]     Attributes         Attribute value of the variable found.
+  @param[in, out] DataSize           Size of Data found. If size is less than the
+                                     data, this value contains the required size.
+  @param[out]     Data               Data pointer.
+
+  @retval EFI_INVALID_PARAMETER      Invalid parameter.
+  @retval EFI_SUCCESS                Find the specified variable.
+  @retval EFI_NOT_FOUND              Not found.
+  @retval EFI_BUFFER_TO_SMALL        DataSize is too small for the result.
+
+**/
+EFI_STATUS
+EFIAPI
+RuntimeServiceGetVariable (
+  IN      CHAR16                            *VariableName,
+  IN      EFI_GUID                          *VendorGuid,
+  OUT     UINT32                            *Attributes OPTIONAL,
+  IN OUT  UINTN                             *DataSize,
+  OUT     VOID                              *Data
+  )
+{
+  EFI_STATUS                                Status;
+
+  if (VariableName == NULL || VendorGuid == NULL || DataSize == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+  if (VariableName[0] == 0) {
+    return EFI_NOT_FOUND;
+  }
+
+  AcquireLockOnlyAtBootTime (&mVariableServicesLock);
+  if (FeaturePcdGet (PcdEnableVariableRuntimeCache)) {
+    Status = FindVariableInRuntimeCache (VariableName, VendorGuid, Attributes, DataSize, Data);
+  } else {
+    Status = FindVariableInSmm (VariableName, VendorGuid, Attributes, DataSize, Data);
+  }
   ReleaseLockOnlyAtBootTime (&mVariableServicesLock);
+
   return Status;
 }
 
-
 /**
   This code Finds the Next available variable.
 
@@ -870,6 +1153,17 @@ OnReadyToBoot (
   //
   SendCommunicateBuffer (0);
 
+  //
+  // Install the system configuration table for variable info data captured
+  //
+  if (FeaturePcdGet (PcdEnableVariableRuntimeCache) && FeaturePcdGet (PcdVariableCollectStatistics)) {
+    if (mVariableAuthFormat) {
+      gBS->InstallConfigurationTable (&gEfiAuthenticatedVariableGuid, mVariableInfo);
+    } else {
+      gBS->InstallConfigurationTable (&gEfiVariableGuid, mVariableInfo);
+    }
+  }
+
   gBS->CloseEvent (Event);
 }
 
@@ -893,6 +1187,9 @@ VariableAddressChangeEvent (
 {
   EfiConvertPointer (0x0, (VOID **) &mVariableBuffer);
   EfiConvertPointer (0x0, (VOID **) &mSmmCommunication);
+  EfiConvertPointer (EFI_OPTIONAL_PTR, (VOID **) &mVariableRuntimeHobCacheBuffer);
+  EfiConvertPointer (EFI_OPTIONAL_PTR, (VOID **) &mVariableRuntimeNvCacheBuffer);
+  EfiConvertPointer (EFI_OPTIONAL_PTR, (VOID **) &mVariableRuntimeVolatileCacheBuffer);
 }
 
 /**
@@ -969,6 +1266,159 @@ Done:
   return Status;
 }
 
+/**
+  This code gets information needed from SMM for runtime cache initialization.
+
+  @param[out] TotalHobStorageSize         Output pointer for the total HOB storage size in bytes.
+  @param[out] TotalNvStorageSize          Output pointer for the total non-volatile storage size in bytes.
+  @param[out] TotalVolatileStorageSize    Output pointer for the total volatile storage size in bytes.
+  @param[out] AuthenticatedVariableUsage  Output pointer that indicates if authenticated variables are to be used.
+
+  @retval EFI_SUCCESS                     Retrieved the size successfully.
+  @retval EFI_INVALID_PARAMETER           TotalNvStorageSize parameter is NULL.
+  @retval EFI_OUT_OF_RESOURCES            The memory resources needed for a CommBuffer are not available.
+  @retval Others                          Could not retrieve the size successfully.
+
+**/
+EFI_STATUS
+GetRuntimeCacheInfo (
+  OUT UINTN                         *TotalHobStorageSize,
+  OUT UINTN                         *TotalNvStorageSize,
+  OUT UINTN                         *TotalVolatileStorageSize,
+  OUT BOOLEAN                       *AuthenticatedVariableUsage
+  )
+{
+  EFI_STATUS                                          Status;
+  SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO     *SmmGetRuntimeCacheInfo;
+  EFI_SMM_COMMUNICATE_HEADER                          *SmmCommunicateHeader;
+  SMM_VARIABLE_COMMUNICATE_HEADER                     *SmmVariableFunctionHeader;
+  UINTN                                               CommSize;
+  UINT8                                               *CommBuffer;
+
+  SmmGetRuntimeCacheInfo = NULL;
+  CommBuffer = mVariableBuffer;
+
+  if (TotalHobStorageSize == NULL || TotalNvStorageSize == NULL || TotalVolatileStorageSize == NULL || AuthenticatedVariableUsage == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  if (CommBuffer == NULL) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  AcquireLockOnlyAtBootTime (&mVariableServicesLock);
+
+  CommSize = SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + sizeof (SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO);
+  ZeroMem (CommBuffer, CommSize);
+
+  SmmCommunicateHeader = (EFI_SMM_COMMUNICATE_HEADER *) CommBuffer;
+  CopyGuid (&SmmCommunicateHeader->HeaderGuid, &gEfiSmmVariableProtocolGuid);
+  SmmCommunicateHeader->MessageLength = SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + sizeof (SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO);
+
+  SmmVariableFunctionHeader = (SMM_VARIABLE_COMMUNICATE_HEADER *) SmmCommunicateHeader->Data;
+  SmmVariableFunctionHeader->Function = SMM_VARIABLE_FUNCTION_GET_RUNTIME_CACHE_INFO;
+  SmmGetRuntimeCacheInfo = (SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO *) SmmVariableFunctionHeader->Data;
+
+  //
+  // Send data to SMM.
+  //
+  Status = mSmmCommunication->Communicate (mSmmCommunication, CommBuffer, &CommSize);
+  ASSERT_EFI_ERROR (Status);
+  if (CommSize <= SMM_VARIABLE_COMMUNICATE_HEADER_SIZE) {
+    Status = EFI_BAD_BUFFER_SIZE;
+    goto Done;
+  }
+
+  Status = SmmVariableFunctionHeader->ReturnStatus;
+  if (EFI_ERROR (Status)) {
+    goto Done;
+  }
+
+  //
+  // Get data from SMM.
+  //
+  *TotalHobStorageSize = SmmGetRuntimeCacheInfo->TotalHobStorageSize;
+  *TotalNvStorageSize = SmmGetRuntimeCacheInfo->TotalNvStorageSize;
+  *TotalVolatileStorageSize = SmmGetRuntimeCacheInfo->TotalVolatileStorageSize;
+  *AuthenticatedVariableUsage = SmmGetRuntimeCacheInfo->AuthenticatedVariableUsage;
+
+Done:
+  ReleaseLockOnlyAtBootTime (&mVariableServicesLock);
+  return Status;
+}
+
+/**
+  Sends the runtime variable cache context information to SMM.
+
+  @retval EFI_SUCCESS               Retrieved the size successfully.
+  @retval EFI_INVALID_PARAMETER     TotalNvStorageSize parameter is NULL.
+  @retval EFI_OUT_OF_RESOURCES      The memory resources needed for a CommBuffer are not available.
+  @retval Others                    Could not retrieve the size successfully.;
+
+**/
+EFI_STATUS
+SendRuntimeVariableCacheContextToSmm (
+  VOID
+  )
+{
+  EFI_STATUS                                                Status;
+  SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT   *SmmRuntimeVarCacheContext;
+  EFI_SMM_COMMUNICATE_HEADER                                *SmmCommunicateHeader;
+  SMM_VARIABLE_COMMUNICATE_HEADER                           *SmmVariableFunctionHeader;
+  UINTN                                                     CommSize;
+  UINT8                                                     *CommBuffer;
+
+  SmmRuntimeVarCacheContext = NULL;
+  CommBuffer = mVariableBuffer;
+
+  if (CommBuffer == NULL) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  AcquireLockOnlyAtBootTime (&mVariableServicesLock);
+
+  //
+  // Init the communicate buffer. The buffer data size is:
+  // SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + sizeof (SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT);
+  //
+  CommSize = SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + sizeof (SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT);
+  ZeroMem (CommBuffer, CommSize);
+
+  SmmCommunicateHeader = (EFI_SMM_COMMUNICATE_HEADER *) CommBuffer;
+  CopyGuid (&SmmCommunicateHeader->HeaderGuid, &gEfiSmmVariableProtocolGuid);
+  SmmCommunicateHeader->MessageLength = SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + sizeof (SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT);
+
+  SmmVariableFunctionHeader = (SMM_VARIABLE_COMMUNICATE_HEADER *) SmmCommunicateHeader->Data;
+  SmmVariableFunctionHeader->Function = SMM_VARIABLE_FUNCTION_INIT_RUNTIME_VARIABLE_CACHE_CONTEXT;
+  SmmRuntimeVarCacheContext = (SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT *) SmmVariableFunctionHeader->Data;
+
+  SmmRuntimeVarCacheContext->RuntimeHobCache = mVariableRuntimeHobCacheBuffer;
+  SmmRuntimeVarCacheContext->RuntimeVolatileCache = mVariableRuntimeVolatileCacheBuffer;
+  SmmRuntimeVarCacheContext->RuntimeNvCache = mVariableRuntimeNvCacheBuffer;
+  SmmRuntimeVarCacheContext->PendingUpdate = &mVariableRuntimeCachePendingUpdate;
+  SmmRuntimeVarCacheContext->ReadLock = &mVariableRuntimeCacheReadLock;
+  SmmRuntimeVarCacheContext->HobFlushComplete = &mHobFlushComplete;
+
+  //
+  // Send data to SMM.
+  //
+  Status = mSmmCommunication->Communicate (mSmmCommunication, CommBuffer, &CommSize);
+  ASSERT_EFI_ERROR (Status);
+  if (CommSize <= SMM_VARIABLE_COMMUNICATE_HEADER_SIZE) {
+    Status = EFI_BAD_BUFFER_SIZE;
+    goto Done;
+  }
+
+  Status = SmmVariableFunctionHeader->ReturnStatus;
+  if (EFI_ERROR (Status)) {
+    goto Done;
+  }
+
+Done:
+  ReleaseLockOnlyAtBootTime (&mVariableServicesLock);
+  return Status;
+}
+
 /**
   Initialize variable service and install Variable Architectural protocol.
 
@@ -985,7 +1435,7 @@ SmmVariableReady (
 {
   EFI_STATUS                                Status;
 
-  Status = gBS->LocateProtocol (&gEfiSmmVariableProtocolGuid, NULL, (VOID **)&mSmmVariable);
+  Status = gBS->LocateProtocol (&gEfiSmmVariableProtocolGuid, NULL, (VOID **) &mSmmVariable);
   if (EFI_ERROR (Status)) {
     return;
   }
@@ -1007,6 +1457,42 @@ SmmVariableReady (
   //
   mVariableBufferPhysical = mVariableBuffer;
 
+  if (FeaturePcdGet (PcdEnableVariableRuntimeCache)) {
+    DEBUG ((DEBUG_INFO, "Variable driver runtime cache is enabled.\n"));
+    //
+    // Allocate runtime variable cache memory buffers.
+    //
+    Status =  GetRuntimeCacheInfo (
+                &mVariableRuntimeHobCacheBufferSize,
+                &mVariableRuntimeNvCacheBufferSize,
+                &mVariableRuntimeVolatileCacheBufferSize,
+                &mVariableAuthFormat
+                );
+    if (!EFI_ERROR (Status)) {
+      Status = InitVariableCache (&mVariableRuntimeHobCacheBuffer, &mVariableRuntimeHobCacheBufferSize);
+      if (!EFI_ERROR (Status)) {
+        Status = InitVariableCache (&mVariableRuntimeNvCacheBuffer, &mVariableRuntimeNvCacheBufferSize);
+        if (!EFI_ERROR (Status)) {
+          Status = InitVariableCache (&mVariableRuntimeVolatileCacheBuffer, &mVariableRuntimeVolatileCacheBufferSize);
+          if (!EFI_ERROR (Status)) {
+            Status = SendRuntimeVariableCacheContextToSmm ();
+            if (!EFI_ERROR (Status)) {
+              SyncRuntimeCache ();
+            }
+          }
+        }
+      }
+      if (EFI_ERROR (Status)) {
+        mVariableRuntimeHobCacheBuffer = NULL;
+        mVariableRuntimeNvCacheBuffer = NULL;
+        mVariableRuntimeVolatileCacheBuffer = NULL;
+      }
+    }
+    ASSERT_EFI_ERROR (Status);
+  } else {
+    DEBUG ((DEBUG_INFO, "Variable driver runtime cache is disabled.\n"));
+  }
+
   gRT->GetVariable         = RuntimeServiceGetVariable;
   gRT->GetNextVariableName = RuntimeServiceGetNextVariableName;
   gRT->SetVariable         = RuntimeServiceSetVariable;
-- 
2.16.2.windows.1


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [PATCH V7 08/10] MdeModulePkg/Variable: Add RT GetNextVariableName() cache support
  2019-11-01 17:34 [PATCH V7 00/10] UEFI Variable SMI Reduction Kubacki, Michael A
                   ` (6 preceding siblings ...)
  2019-11-01 17:34 ` [PATCH V7 07/10] MdeModulePkg/Variable: Add RT GetVariable() cache support Kubacki, Michael A
@ 2019-11-01 17:34 ` Kubacki, Michael A
  2019-11-01 17:34 ` [PATCH V7 09/10] OvmfPkg: Disable variable runtime cache Kubacki, Michael A
                   ` (2 subsequent siblings)
  10 siblings, 0 replies; 14+ messages in thread
From: Kubacki, Michael A @ 2019-11-01 17:34 UTC (permalink / raw)
  To: devel
  Cc: Dandan Bi, Ard Biesheuvel, Eric Dong, Laszlo Ersek, Liming Gao,
	Michael D Kinney, Ray Ni, Jian J Wang, Hao A Wu, Jiewen Yao

https://bugzilla.tianocore.org/show_bug.cgi?id=2220

This change implements the Runtime Service GetNextVariableName()
using the runtime cache in VariableSmmRuntimeDxe. Runtime Service
calls to GetNextVariableName() will no longer trigger a SW SMI
when gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache
is set to TRUE (default value).

Overall system performance and stability will be improved by
eliminating an SMI for these calls as they typically result in a
relatively large number of invocations to retrieve all variable
names in all variable stores present.

Cc: Dandan Bi <dandan.bi@intel.com>
Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Eric Dong <eric.dong@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Cc: Liming Gao <liming.gao@intel.com>
Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Hao A Wu <hao.a.wu@intel.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Signed-off-by: Michael Kubacki <michael.a.kubacki@intel.com>
---
 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c | 137 ++++++++++++++++++--
 1 file changed, 128 insertions(+), 9 deletions(-)

diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c
index 3dee05fded..d525998ae3 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c
@@ -823,7 +823,7 @@ RuntimeServiceGetVariable (
 }
 
 /**
-  This code Finds the Next available variable.
+  Finds the next available variable in a runtime cache variable store.
 
   @param[in, out] VariableNameSize   Size of the variable name.
   @param[in, out] VariableName       Pointer to variable name.
@@ -836,8 +836,81 @@ RuntimeServiceGetVariable (
 
 **/
 EFI_STATUS
-EFIAPI
-RuntimeServiceGetNextVariableName (
+GetNextVariableNameInRuntimeCache (
+  IN OUT  UINTN                             *VariableNameSize,
+  IN OUT  CHAR16                            *VariableName,
+  IN OUT  EFI_GUID                          *VendorGuid
+  )
+{
+  EFI_STATUS              Status;
+  UINTN                   VarNameSize;
+  VARIABLE_HEADER         *VariablePtr;
+  VARIABLE_STORE_HEADER   *VariableStoreHeader[VariableStoreTypeMax];
+
+  Status = EFI_NOT_FOUND;
+
+  //
+  // The UEFI specification restricts Runtime Services callers from invoking the same or certain other Runtime Service
+  // functions prior to completion and return from a previous Runtime Service call. These restrictions prevent
+  // a GetVariable () or GetNextVariable () call from being issued until a prior call has returned. The runtime
+  // cache read lock should always be free when entering this function.
+  //
+  ASSERT (!mVariableRuntimeCacheReadLock);
+
+  CheckForRuntimeCacheSync ();
+
+  mVariableRuntimeCacheReadLock = TRUE;
+  if (!mVariableRuntimeCachePendingUpdate) {
+    //
+    // 0: Volatile, 1: HOB, 2: Non-Volatile.
+    // The index and attributes mapping must be kept in this order as FindVariable
+    // makes use of this mapping to implement search algorithm.
+    //
+    VariableStoreHeader[VariableStoreTypeVolatile] = mVariableRuntimeVolatileCacheBuffer;
+    VariableStoreHeader[VariableStoreTypeHob]      = mVariableRuntimeHobCacheBuffer;
+    VariableStoreHeader[VariableStoreTypeNv]       = mVariableRuntimeNvCacheBuffer;
+
+    Status =  VariableServiceGetNextVariableInternal (
+                VariableName,
+                VendorGuid,
+                VariableStoreHeader,
+                &VariablePtr,
+                mVariableAuthFormat
+                );
+    if (!EFI_ERROR (Status)) {
+      VarNameSize = NameSizeOfVariable (VariablePtr, mVariableAuthFormat);
+      ASSERT (VarNameSize != 0);
+      if (VarNameSize <= *VariableNameSize) {
+        CopyMem (VariableName, GetVariableNamePtr (VariablePtr, mVariableAuthFormat), VarNameSize);
+        CopyMem (VendorGuid, GetVendorGuidPtr (VariablePtr, mVariableAuthFormat), sizeof (EFI_GUID));
+        Status = EFI_SUCCESS;
+      } else {
+        Status = EFI_BUFFER_TOO_SMALL;
+      }
+
+      *VariableNameSize = VarNameSize;
+    }
+  }
+  mVariableRuntimeCacheReadLock = FALSE;
+
+  return Status;
+}
+
+/**
+  Finds the next available variable in a SMM variable store.
+
+  @param[in, out] VariableNameSize   Size of the variable name.
+  @param[in, out] VariableName       Pointer to variable name.
+  @param[in, out] VendorGuid         Variable Vendor Guid.
+
+  @retval EFI_INVALID_PARAMETER      Invalid parameter.
+  @retval EFI_SUCCESS                Find the specified variable.
+  @retval EFI_NOT_FOUND              Not found.
+  @retval EFI_BUFFER_TO_SMALL        DataSize is too small for the result.
+
+**/
+EFI_STATUS
+GetNextVariableNameInSmm (
   IN OUT  UINTN                             *VariableNameSize,
   IN OUT  CHAR16                            *VariableName,
   IN OUT  EFI_GUID                          *VendorGuid
@@ -849,10 +922,6 @@ RuntimeServiceGetNextVariableName (
   UINTN                                           OutVariableNameSize;
   UINTN                                           InVariableNameSize;
 
-  if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {
-    return EFI_INVALID_PARAMETER;
-  }
-
   OutVariableNameSize   = *VariableNameSize;
   InVariableNameSize    = StrSize (VariableName);
   SmmGetNextVariableName = NULL;
@@ -864,8 +933,6 @@ RuntimeServiceGetNextVariableName (
     return EFI_INVALID_PARAMETER;
   }
 
-  AcquireLockOnlyAtBootTime(&mVariableServicesLock);
-
   //
   // Init the communicate buffer. The buffer data size is:
   // SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + PayloadSize.
@@ -924,7 +991,59 @@ RuntimeServiceGetNextVariableName (
   CopyMem (VariableName, SmmGetNextVariableName->Name, SmmGetNextVariableName->NameSize);
 
 Done:
+  return Status;
+}
+
+/**
+  This code Finds the Next available variable.
+
+  @param[in, out] VariableNameSize   Size of the variable name.
+  @param[in, out] VariableName       Pointer to variable name.
+  @param[in, out] VendorGuid         Variable Vendor Guid.
+
+  @retval EFI_INVALID_PARAMETER      Invalid parameter.
+  @retval EFI_SUCCESS                Find the specified variable.
+  @retval EFI_NOT_FOUND              Not found.
+  @retval EFI_BUFFER_TO_SMALL        DataSize is too small for the result.
+
+**/
+EFI_STATUS
+EFIAPI
+RuntimeServiceGetNextVariableName (
+  IN OUT  UINTN                             *VariableNameSize,
+  IN OUT  CHAR16                            *VariableName,
+  IN OUT  EFI_GUID                          *VendorGuid
+  )
+{
+  EFI_STATUS              Status;
+  UINTN                   MaxLen;
+
+  Status = EFI_NOT_FOUND;
+
+  if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  //
+  // Calculate the possible maximum length of name string, including the Null terminator.
+  //
+  MaxLen = *VariableNameSize / sizeof (CHAR16);
+  if ((MaxLen == 0) || (StrnLenS (VariableName, MaxLen) == MaxLen)) {
+    //
+    // Null-terminator is not found in the first VariableNameSize bytes of the input VariableName buffer,
+    // follow spec to return EFI_INVALID_PARAMETER.
+    //
+    return EFI_INVALID_PARAMETER;
+  }
+
+  AcquireLockOnlyAtBootTime (&mVariableServicesLock);
+  if (FeaturePcdGet (PcdEnableVariableRuntimeCache)) {
+    Status = GetNextVariableNameInRuntimeCache (VariableNameSize, VariableName, VendorGuid);
+  } else {
+    Status = GetNextVariableNameInSmm (VariableNameSize, VariableName, VendorGuid);
+  }
   ReleaseLockOnlyAtBootTime (&mVariableServicesLock);
+
   return Status;
 }
 
-- 
2.16.2.windows.1


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [PATCH V7 09/10] OvmfPkg: Disable variable runtime cache
  2019-11-01 17:34 [PATCH V7 00/10] UEFI Variable SMI Reduction Kubacki, Michael A
                   ` (7 preceding siblings ...)
  2019-11-01 17:34 ` [PATCH V7 08/10] MdeModulePkg/Variable: Add RT GetNextVariableName() " Kubacki, Michael A
@ 2019-11-01 17:34 ` Kubacki, Michael A
  2019-11-01 17:34 ` [PATCH V7 10/10] MdeModulePkg: Enable variable runtime cache by default Kubacki, Michael A
  2019-11-01 22:19 ` [PATCH V7 00/10] UEFI Variable SMI Reduction Laszlo Ersek
  10 siblings, 0 replies; 14+ messages in thread
From: Kubacki, Michael A @ 2019-11-01 17:34 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Laszlo Ersek, Liming Gao, Jordan Justen, Hao A Wu

Sets gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache
to FALSE in OvmfPkgIa32.dsc, OvmfPkgIa32X64.dsc, and OvmfPkgX64.dsc
so that when SMM_REQUIRE is TRUE, the SMM variable driver will not
use the runtime variable cache.

This is done for OvmfPkg because it currently depends upon a SMM
variable GetVariable ()implementation as a simple method to exercise
the SMM driver stack. This allows the following commands to be used
for variables such as Boot####, BootOrder, and BootNext to test SMM
timing and stability differences on the BSP (e.g. CPU#0) vs an
AP (e.g. CPU#1).
 # taskset -c 0 efibootmgr
 # taskset -c 1 efibootmgr

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Laszlo Ersek <lersek@redhat.com>
Cc: Liming Gao <liming.gao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Hao A Wu <hao.a.wu@intel.com>
Signed-off-by: Michael Kubacki <michael.a.kubacki@intel.com>
---
 OvmfPkg/OvmfPkgIa32.dsc    | 1 +
 OvmfPkg/OvmfPkgIa32X64.dsc | 1 +
 OvmfPkg/OvmfPkgX64.dsc     | 1 +
 3 files changed, 3 insertions(+)

diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc
index 05bb6ae136..d350b75630 100644
--- a/OvmfPkg/OvmfPkgIa32.dsc
+++ b/OvmfPkg/OvmfPkgIa32.dsc
@@ -431,6 +431,7 @@
 !if $(SMM_REQUIRE) == TRUE
   gUefiOvmfPkgTokenSpaceGuid.PcdSmmSmramRequire|TRUE
   gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmEnableBspElection|FALSE
+  gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE
 !endif
 
 [PcdsFixedAtBuild]
diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
index 4a75a0332e..1ef82cafe4 100644
--- a/OvmfPkg/OvmfPkgIa32X64.dsc
+++ b/OvmfPkg/OvmfPkgIa32X64.dsc
@@ -436,6 +436,7 @@
 !if $(SMM_REQUIRE) == TRUE
   gUefiOvmfPkgTokenSpaceGuid.PcdSmmSmramRequire|TRUE
   gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmEnableBspElection|FALSE
+  gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE
 !endif
 
 [PcdsFixedAtBuild]
diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
index ed54181180..232815c08e 100644
--- a/OvmfPkg/OvmfPkgX64.dsc
+++ b/OvmfPkg/OvmfPkgX64.dsc
@@ -436,6 +436,7 @@
 !if $(SMM_REQUIRE) == TRUE
   gUefiOvmfPkgTokenSpaceGuid.PcdSmmSmramRequire|TRUE
   gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmEnableBspElection|FALSE
+  gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE
 !endif
 
 [PcdsFixedAtBuild]
-- 
2.16.2.windows.1


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [PATCH V7 10/10] MdeModulePkg: Enable variable runtime cache by default
  2019-11-01 17:34 [PATCH V7 00/10] UEFI Variable SMI Reduction Kubacki, Michael A
                   ` (8 preceding siblings ...)
  2019-11-01 17:34 ` [PATCH V7 09/10] OvmfPkg: Disable variable runtime cache Kubacki, Michael A
@ 2019-11-01 17:34 ` Kubacki, Michael A
  2019-11-01 22:19 ` [PATCH V7 00/10] UEFI Variable SMI Reduction Laszlo Ersek
  10 siblings, 0 replies; 14+ messages in thread
From: Kubacki, Michael A @ 2019-11-01 17:34 UTC (permalink / raw)
  To: devel
  Cc: Dandan Bi, Ard Biesheuvel, Eric Dong, Laszlo Ersek, Liming Gao,
	Michael D Kinney, Ray Ni, Jian J Wang, Hao A Wu, Jiewen Yao

This change enables the variable runtime cache by default by setting
gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache in
MdeModulePkg.dec to TRUE.

Cc: Dandan Bi <dandan.bi@intel.com>
Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Eric Dong <eric.dong@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Cc: Liming Gao <liming.gao@intel.com>
Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Hao A Wu <hao.a.wu@intel.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Signed-off-by: Michael Kubacki <michael.a.kubacki@intel.com>
---
 MdeModulePkg/MdeModulePkg.dec | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec
index 3ef8fe7644..1e964f5903 100644
--- a/MdeModulePkg/MdeModulePkg.dec
+++ b/MdeModulePkg/MdeModulePkg.dec
@@ -651,7 +651,7 @@
   #   TRUE  - The UEFI variable runtime cache is enabled.<BR>
   #   FALSE - The UEFI variable runtime cache is disabled.<BR>
   # @Prompt Enable the UEFI variable runtime cache.
-  gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE|BOOLEAN|0x00010039
+  gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|TRUE|BOOLEAN|0x00010039
 
   ## Indicates if the statistics about variable usage will be collected. This information is
   #  stored as a vendor configuration table into the EFI system table.
-- 
2.16.2.windows.1


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* Re: [PATCH V7 00/10] UEFI Variable SMI Reduction
  2019-11-01 17:34 [PATCH V7 00/10] UEFI Variable SMI Reduction Kubacki, Michael A
                   ` (9 preceding siblings ...)
  2019-11-01 17:34 ` [PATCH V7 10/10] MdeModulePkg: Enable variable runtime cache by default Kubacki, Michael A
@ 2019-11-01 22:19 ` Laszlo Ersek
  2019-11-01 23:17   ` Kubacki, Michael A
  10 siblings, 1 reply; 14+ messages in thread
From: Laszlo Ersek @ 2019-11-01 22:19 UTC (permalink / raw)
  To: Michael Kubacki, devel
  Cc: Dandan Bi, Ard Biesheuvel, Eric Dong, Liming Gao,
	Michael D Kinney, Ray Ni, Jian J Wang, Hao A Wu, Jiewen Yao

Hello Michael,

On 11/01/19 18:34, Michael Kubacki wrote:
> REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2220
> 
> V7 Changes:
>  [PATCH V6 07/10] MdeModulePkg/Variable: Add RT GetVariable() cache support
>  * Remove VariableRuntimeCache.c and VariableRuntimeCache.h from
>    VariableSmmRuntimeDxe.inf since they are not needed to build the module.
> 
> V6 Changes:
>  [PATCH V5 07/10] MdeModulePkg/Variable: Add RT GetVariable() cache support
>  The most significant change is:
>  * Free mVariableRuntimeHobCacheBuffer in CheckForRuntimeCacheSync () in
>    VariableSmmRuntimeDxe.c with FreePages () instead of FreePool ().
>  This issue was not found in earlier testing because on the initial set of
>  platforms tested, the variable HOB flush was finished prior to the variable
>  HOB runtime cache buffer being allocated so the FreePages () call was not
>  executed.
> 
>  The remaining changes did not affect testing but are included for robustness:
>  * Pass EFI_OPTIONAL_PTR for the DebugDisposition type in the EfiConvertPointer ()
>    calls for mVariableRuntimeHobCacheBuffer, mVariableRuntimeNvCacheBuffer, and
>    mVariableRuntimeVolatileCacheBuffer in VariableAddressChangeEvent () in
>    VariableSmmRuntimeDxe.c as these buffers will not be allocated if the runtime
>    cache is disabled.
>  * In the SMM_VARIABLE_FUNCTION_INIT_RUNTIME_VARIABLE_CACHE_CONTEXT case in
>    SmmVariableHandler () in VariableSmm.c, explicitly verify that
>    VariableRuntimeHobCache.Store is not NULL in addition to checking that
>    VariableGlobal.HobVariableBase is not set to zero (variable HOB is flushed)
>    before writing to VariableRuntimeHobCache.Store.
> 
> V5 Changes:
>  [PATCH V4 07/10] MdeModulePkg/Variable: Add RT GetVariable() cache support
>  * Increased validation of the runtime buffers passed in the SMM comm buffer
>    SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT structure to the
>    SMM_VARIABLE_FUNCTION_INIT_RUNTIME_VARIABLE_CACHE_CONTEXT function in
>    SmmVariableHandler () in VariableSmm.c.
>  * Most notably, each runtime buffer given is checked to ensure its memory
>    range does not overlap with SMRAM ranges via VariableSmmIsBufferOutsideSmmValid ().
> 
> V4 Changes:
>  [PATCH V3 7/9] MdeModulePkg/Variable: Add RT GetVariable() cache support
>  * Set gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache to FALSE
>    by default in MdeModulePkg.dec.
> 
>  * Added a new patch to set gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache
>    to TRUE at the end of the patch series. This allows someone to bisect an issue at
>    patch #7 or patch #8 in the series with no change in variable caching behavior. The
>    runtime cache variable logic would be applied explicitly in V4 patch #10.

I gave my R-b for the OvmfPkg patch in the v4 posting:

https://edk2.groups.io/g/devel/message/48979

(alternative link:

http://mid.mail-archive.com/b89583ed-06ef-ccd2-2e29-d054f581ea6a@redhat.com
)

In the v5 posting -- assuming you had not changed that specific OvmfPkg
patch, relative to v4 -- you should have picked up my R-b, and carried
it forward ever since (to the present v7). Basically, do a git-rebase,
select the "reword" action for the patch, then cut&paste my R-b from my
v4 review email to the bottom of the commit message. Then every further
posting will contain it.

If there *have* been changes to the patch, relative to v4, then it's
indeed right to drop (or simply not pick up) my R-b. FWIW, the changelog
above does not suggest the particular patch has seen any changes since v4.

Thanks!
Laszlo

> 
> V3 Changes:
>  [PATCH V2 1/9] MdeModulePkg/Variable: Consolidate common parsing functions
>  * Removed GUIDs added to VariableStandaloneMm.inf that are not required.
>  * Added more details to the commit message describing the criteria of
>    moving the chosen functions to VariableParsing.c.
> 
>  [PATCH V2 2/9] MdeModulePkg/Variable: Parameterize GetNextVariableEx() store list
>  * RenamedGetNextVariableEx () to VariableServiceGetNextVariableInternal ()
>  * Updated comments in VariableServiceGetNextVariableInternal () to refer to
>    "FindVariablEx ()" instead of "FindVariable ()" since FindVariableEx ()
>    is not used in the function.
> 
>  [PATCH V2 3/9] MdeModulePkg/Variable: Parameterize VARIABLE_INFO_ENTRY buffer
>  * Updated the commit message to clarify the message "structure can be updated
>    outside the fixed global variable".
> 
>  [edk2-devel] [PATCH V2 4/9] MdeModulePkg/Variable: Add local auth status in VariableParsing
>  * Remove the function InitVariableParsing ()
>  * Remove the mAuthFormat global variable and instead add a BOOLEAN parameter
>    to all functions that require variable authentication information  to
>    indicate if authenticated variables are used.
>    * This allows the authenticated variable status to be tracked in one place in
>      each variable driver in the SMM variable solution (VariableSmmRuntimeDxe
>      and VariableSmm).
> 
>  [edk2-devel] [PATCH V2 5/9] MdeModulePkg/Variable: Add a file for NV variable functions
>  * Added the following non-volatile related functions to VariableNonVolatile.c
>    from Variable.c:
>    * InitRealNonVolatileVariableStore ()
>    * InitEmuNonVolatileVariableStore ()
>    * InitNonVolatileVariableStore ()
> 
>  [edk2-devel] [PATCH V2 7/9] MdeModulePkg/Variable: Add RT GetVariable() cache support
>  * Added a FeaturePCD to control enabling the runtime variable cache -
>    gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache.
>  * Removed usage of the TimerLib and the wait to acquire
>    mVariableRuntimeCacheReadLock. Can rely on the UEFI specification
>    restrictions on Runtime Services callers.
>  * Removed the EFIAPI keyword from internal functions.
>  * Removed PCDs in VariableSmmRuntimeDxe.inf not required.
>  * Removed the HobVariableBackupBase variable no longer required.
>  * Renamed SynchronizeRuntimeVariableCacheEx () to better reflect usage.
>  * Renamed functions in VariableRuntimeCache.c to better reflect usage.
>  * Introduced a local variable in FlushPendingRuntimeVariableCacheUpdates ()
>    to reduce duplication of 
>    mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.
>  * Corrected the macro used in SmmVariableHandler () to
>    SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT.
>  * Remove usage of the EDKII_PI_SMM_COMMUNICATION_REGION_TABLE to acquire a
>    CommBuffer from the EFI System Table and use the same runtime CommBuffer
>    allocated for variable SMM communicate calls.
> 
>  [PATCH V2 8/9] MdeModulePkg/Variable: Add RT GetNextVariableName() cache support
>  * Removed usage of the TimerLib and the wait to acquire
>    mVariableRuntimeCacheReadLock. Can rely on the UEFI specification restrictions
>    on Runtime Services callers.
> 
>  * Added a new patch to disable gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache
>    for all OvmfPkg package builds as requested by maintainer Laszlo Ersek.
> 
> V2 Changes:
> 
> Patch #1 in V1 both moved functions to VariableParsing.c and modified some
> functionality in those functions. In V2, the functions are first moved and
> then functionality is modified in subsequent patches. This resulted in the
> following new patches in the V2 patch series:
> 
>  1. MdeModulePkg/Variable: Parameterize GetNextVariableEx() store list
>  2. MdeModulePkg/Variable: Parameterize VARIABLE_INFO_ENTRY buffer
>  3. MdeModulePkg/Variable: Add local auth status in VariableParsing
>  4. MdeModulePkg/Variable: Add a file for NV variable functions
> 
> Apart from this refactor in the patches, no functionally impacting changes
> were made.
> 
> Overview
> ---------
> This patch series reduces SMM usage when using VariableSmmRuntimeDxe with
> VariableSmm. It does so by eliminating SMM usage for runtime service
> GetVariable () and GetNextVariableName () invocations. Most UEFI variable
> usage in typical systems after the variable store is initialized
> (e.g. manufacturing boots) is due to GetVariable ( ) and
> GetNextVariableName () not SetVariable (). GetVariable () calls can regularly
> exceed 100 per boot while SetVariable () calls typically remain less than 10
> per boot. By focusing on the common case, the majority of overhead associated
> with SMM can be avoided while still using existing and proven code for
> operations such as variable authentication that require an isolated execution
> environment.
> 
>  * Advantage: Reduces overall system SMM usage
>  * Disadvantage: Requires more Runtime data memory usage
> 
> The runtime cache behavior described for this patch series is enabled by
> default but can be disabled with a new FeaturePCD added to MdeModulePkg.dec:
>   gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache
> 
> The reaminder of this blurb describes the changes and behavior when the PCD
> is set to TRUE.
> 
> Initial Performance Observations
> ---------------------------------
>  * With these proposed changes, an Intel Atom based SoC saw GetVariable ( )
>    time for an existing variable reduce from ~220us to ~5us.
> 
> Major Changes
> --------------
>  1. Two UEFI variable caches will be maintained.
>      a. "Runtime Cache" - Maintained in VariableSmmRuntimeDxe. Used to serve
>          runtime service GetVariable () and GetNextVariableName () callers.
>      b. "SMM cache" - Maintained in VariableSmm to service SMM GetVariable ()
>          and GetNextVariableName () callers.
>          i. A cache in SMRAM is retained so SMM modules do not operate on data
>             outside SMRAM.
>  2. A new UEFI variable read and write flow will be used as described below.
> 
> At any given time, the two caches would be coherent. On a variable write, the
> runtime cache is only updated after validation in SMM and, in the case of a
> non-volatile UEFI variable, the variable must also be successfully written to
> non-volatile storage.
> 
> Prior RFC Feedback Addressed
> -----------------------------
> RFC sent Sept. 5, 2019: https://edk2.groups.io/g/devel/message/46939
> 
> 1. UEFI variable data retrieval from a ring 0 buffer
> 
>    A common concern with this proposed set of changes is the potential security
>    threat presented by serving runtime services callers from a ring 0 memory
>    buffer of EfiRuntimeServicesData type. The conclusion was that this change
>    does not fundamentally alter the attack surface. The UEFI variable Runtime
>    Services are invoked from ring 0 and the data already travels through ring
>    0 buffers (such as the SMM communicate buffer) to reach the caller. Even
>    today if ring 0 is assumed to be malicious, the malicious code may keep one
>    AP in a loop to monitor the communication data, when the BSP gets an
>    (authenticated) variable. When the communication buffer is updated and the
>    status is set to EFI_SUCCESS, the AP may modify the communication buffer
>    contents such the tampered data is returned to the BSP caller. Or an
>    interrupt handler on the BSP may alter the communication buffer contents
>    before the data is returned to the caller. In summary, this was not found to
>    introduce any attack not possible today.
> 
> 2. VarCheckLib impact
> 
>    VarCheckLib plays a role in SetVariable () calls. This patch series only
>    changes GetVariable () behavior. Therefore, VarCheckLib is expected to
>    have no impact due to these changes.
> 
> Testing Performed
> ------------------
> This code was tested with the master branch of edk2 on an Intel Kaby Lake U
> and Intel Whiskey Lake U reference validation platform. The set of tests
> performed included:
> 
> 1.  Boot from S5 to Windows 10 OS with SMM variables enabled and
>     the variable runtime cache enabled.
> 2.  Boot from S5 to Ubuntu 18.04.1 LTS with SMM variable enabled
>     and the variable runtime cache enabled.
> 3.  Boot from S5 to Windows 10 OS with SMM variables enabled and
>     the variable runtime cache disabled.
> 4.  Boot from S5 to Ubuntu 18.04.1 LTS with SMM variable enabled
>     and the variable runtime cache disabled.
> 5.  Boot from S5 to EFI shell with DXE variables enabled.
>     (commit 2de1f611be broke OvmfPkgIa32X64 boot regardless of
>      this patch series; testing without this commit was successful)
> 6.  Dump UEFI variable store at shell with dmpstore to verify contents.
> 7.  Dump NvStorage FV from SPI flash after boot to verify contents written.
> 8.  Dump UEFI variable statistics with VariableInfo at shell.
> 9.  Boot with emulated variables enabled.
> 10. Cycles of adding and deleting a UEFI variable to verify cache correctness.
> 11. Set OsIndications to stop at FW UI to verify cache load of non-volatile
>     contents.
> 
> Why Keep SMM on Variable Writes
> --------------------------------
>  * SMM provides a ubiquitous isolated execution environment in x86 for
>    authenticated UEFI variables.
>  * BIOS region SPI flash write restrictions to SMM in platforms today can
>    be retained.
> 
> Today's UEFI Variable Cache (for reference)
> --------------------------------------------
>  * Maintained in SMRAM via VariableSmm.
>  * A "write-through" cache of variable data in the form of a UEFI variable
>    store.
>  * Non-volatile and volatile variables are maintained in separate buffers
>   (variable stores).
> 
> Runtime & SMM Cache Coherency
> ------------------------------
> The non-volatile cache should always accurately reflect non-volatile storage
> contents (done today) and the "SMM cache" and "Runtime cache" should always be
> coherent on access. The runtime cache is updated by VariableSmm.
> 
> Updating both caches from within a SMM SetVariable () operation is fairly
> straightforward but a race condition can occur if an SMI occurs during the
> execution of runtime code reading from the runtime cache. To handle this case,
> a runtime cache read lock is introduced that explicitly moves pending updates
> from SMM to the runtime cache if an SMM update occurs while the runtime cache
> is locked. Note that it is not expected a Runtime services call will interrupt
> SMM processing since all CPU cores rendezvous in SMM.
> 
> New Key Elements for Coherence
> -------------------------------
> Runtime DXE (VariableSmmRuntimeDxe)
>  1. RuntimeCacheReadLock - A global lock used to lock read access to the
>                            runtime cache.
>  2. RuntimeCachePendingUpdate - A global flag used to notify runtime code of a
>                                 pending cache update in SMM.
> 
> SMM (VariableSmm)
>  1. FlushRuntimeCachePendingUpdate SMI - A SW SMI handler that synchronizes
>                                          the runtime cache buffer with the SMM
>                                          cache buffer.
> 
> Proposed Runtime DXE Read Flow
> -------------------------------
>  1. Acquire RuntimeCacheReadLock
>  2. If RuntimeCachePendingUpdate flag (rare) is set then:
>      2.a. Trigger FlushRuntimeCachePendingUpdate SMI
>      2.b. Verify RuntimeCachePendingUpdate flag is cleared
>  3. Perform read from RuntimeCache
>  4. Release RuntimeCacheReadLock
> 
> Proposed FlushRuntimeCachePendingUpdate SMI
> --------------------------------------------
>  1. If RuntimeCachePendingUpdate flag is not set:
>      1.a. Return
>  2. Copy the data at RuntimeCachePendingOffset of RuntimeCachePendingLength to
>     RuntimeCache
>  3. Clear the RuntimeCachePendingUpdate flag
> 
> Proposed SMM Write Flow
> ------------------------
>  1. Perform variable authentication and non-volatile write. If either fail,
>     return an error to the caller.
>  2. If RuntimeCacheReadLock is set then:
>      2.a. Set RuntimeCachePendingUpdate flag
>      2.b. Update RuntimeCachePendingOffset and RuntimeCachePendingLength to
>           cover the a superset of the pending chunk (for simplicity, the
>           entire variable store is currently synchronized).
> 3. Else:
>      3.a. Update RuntimeCache
> 4. Update SmmCache
>      - Note: RT read cannot occur during SMI processing since all cores are
>              locked in SMM.
> 
> Cc: Dandan Bi <dandan.bi@intel.com>
> Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
> Cc: Eric Dong <eric.dong@intel.com>
> Cc: Laszlo Ersek <lersek@redhat.com>
> Cc: Liming Gao <liming.gao@intel.com>
> Cc: Michael D Kinney <michael.d.kinney@intel.com>
> Cc: Ray Ni <ray.ni@intel.com>
> Cc: Jian J Wang <jian.j.wang@intel.com>
> Cc: Hao A Wu <hao.a.wu@intel.com>
> Cc: Jiewen Yao <jiewen.yao@intel.com>
> Signed-off-by: Michael Kubacki <michael.a.kubacki@intel.com>
> 
> Michael Kubacki (10):
>   MdeModulePkg/Variable: Consolidate common parsing functions
>   MdeModulePkg/Variable: Parameterize GetNextVariableInternal () stores
>   MdeModulePkg/Variable: Parameterize VARIABLE_INFO_ENTRY buffer
>   MdeModulePkg/Variable: Parameterize auth status in VariableParsing
>   MdeModulePkg/Variable: Add a file for NV variable functions
>   MdeModulePkg VariableInfo: Always consider RT DXE and SMM stats
>   MdeModulePkg/Variable: Add RT GetVariable() cache support
>   MdeModulePkg/Variable: Add RT GetNextVariableName() cache support
>   OvmfPkg: Disable variable runtime cache
>   MdeModulePkg: Enable variable runtime cache by default
> 
>  MdeModulePkg/MdeModulePkg.dec                                        |   12 +
>  OvmfPkg/OvmfPkgIa32.dsc                                              |    1 +
>  OvmfPkg/OvmfPkgIa32X64.dsc                                           |    1 +
>  OvmfPkg/OvmfPkgX64.dsc                                               |    1 +
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf    |    6 +
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf           |    6 +
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf |   18 +-
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf  |    6 +
>  MdeModulePkg/Include/Guid/SmmVariableCommon.h                        |   29 +-
>  MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h                |  151 +--
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.h     |   67 +
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h         |  347 +++++
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.h    |   51 +
>  MdeModulePkg/Application/VariableInfo/VariableInfo.c                 |   37 +-
>  MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c                | 1373 ++++----------------
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c           |   24 +-
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.c     |  334 +++++
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c         |  786 +++++++++++
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.c    |  153 +++
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c             |  195 ++-
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c   |  655 +++++++++-
>  21 files changed, 2924 insertions(+), 1329 deletions(-)
>  create mode 100644 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.h
>  create mode 100644 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h
>  create mode 100644 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.h
>  create mode 100644 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.c
>  create mode 100644 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c
>  create mode 100644 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.c
> 


^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH V7 00/10] UEFI Variable SMI Reduction
  2019-11-01 22:19 ` [PATCH V7 00/10] UEFI Variable SMI Reduction Laszlo Ersek
@ 2019-11-01 23:17   ` Kubacki, Michael A
  0 siblings, 0 replies; 14+ messages in thread
From: Kubacki, Michael A @ 2019-11-01 23:17 UTC (permalink / raw)
  To: Laszlo Ersek, devel@edk2.groups.io
  Cc: Bi, Dandan, Ard Biesheuvel, Dong, Eric, Gao, Liming,
	Kinney, Michael D, Ni, Ray, Wang, Jian J, Wu, Hao A, Yao, Jiewen

Hi Laszlo,

I did not make any changes to the OvmfPkg patch and I forgot to carry forward the R-b.
I'll keep that in mind in the future.

For V7, I request the MdeModulePkg maintainers please add the R-b for the patches
not changed. If this is not acceptable, I will be happy to send out a patch series
with all of the R-b present.

Thanks,
Michael

> -----Original Message-----
> From: Laszlo Ersek <lersek@redhat.com>
> Sent: Friday, November 1, 2019 3:19 PM
> To: Kubacki, Michael A <michael.a.kubacki@intel.com>;
> devel@edk2.groups.io
> Cc: Bi, Dandan <dandan.bi@intel.com>; Ard Biesheuvel
> <ard.biesheuvel@linaro.org>; Dong, Eric <eric.dong@intel.com>; Gao, Liming
> <liming.gao@intel.com>; Kinney, Michael D <michael.d.kinney@intel.com>;
> Ni, Ray <ray.ni@intel.com>; Wang, Jian J <jian.j.wang@intel.com>; Wu, Hao
> A <hao.a.wu@intel.com>; Yao, Jiewen <jiewen.yao@intel.com>
> Subject: Re: [PATCH V7 00/10] UEFI Variable SMI Reduction
> 
> Hello Michael,
> 
> On 11/01/19 18:34, Michael Kubacki wrote:
> > REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2220
> >
> > V7 Changes:
> >  [PATCH V6 07/10] MdeModulePkg/Variable: Add RT GetVariable() cache
> > support
> >  * Remove VariableRuntimeCache.c and VariableRuntimeCache.h from
> >    VariableSmmRuntimeDxe.inf since they are not needed to build the
> module.
> >
> > V6 Changes:
> >  [PATCH V5 07/10] MdeModulePkg/Variable: Add RT GetVariable() cache
> > support  The most significant change is:
> >  * Free mVariableRuntimeHobCacheBuffer in CheckForRuntimeCacheSync
> () in
> >    VariableSmmRuntimeDxe.c with FreePages () instead of FreePool ().
> >  This issue was not found in earlier testing because on the initial
> > set of  platforms tested, the variable HOB flush was finished prior to
> > the variable  HOB runtime cache buffer being allocated so the
> > FreePages () call was not  executed.
> >
> >  The remaining changes did not affect testing but are included for
> robustness:
> >  * Pass EFI_OPTIONAL_PTR for the DebugDisposition type in the
> EfiConvertPointer ()
> >    calls for mVariableRuntimeHobCacheBuffer,
> mVariableRuntimeNvCacheBuffer, and
> >    mVariableRuntimeVolatileCacheBuffer in VariableAddressChangeEvent ()
> in
> >    VariableSmmRuntimeDxe.c as these buffers will not be allocated if the
> runtime
> >    cache is disabled.
> >  * In the
> SMM_VARIABLE_FUNCTION_INIT_RUNTIME_VARIABLE_CACHE_CONTEXT
> case in
> >    SmmVariableHandler () in VariableSmm.c, explicitly verify that
> >    VariableRuntimeHobCache.Store is not NULL in addition to checking that
> >    VariableGlobal.HobVariableBase is not set to zero (variable HOB is
> flushed)
> >    before writing to VariableRuntimeHobCache.Store.
> >
> > V5 Changes:
> >  [PATCH V4 07/10] MdeModulePkg/Variable: Add RT GetVariable() cache
> > support
> >  * Increased validation of the runtime buffers passed in the SMM comm
> buffer
> >
> SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT
> structure to the
> >
> SMM_VARIABLE_FUNCTION_INIT_RUNTIME_VARIABLE_CACHE_CONTEXT
> function in
> >    SmmVariableHandler () in VariableSmm.c.
> >  * Most notably, each runtime buffer given is checked to ensure its
> memory
> >    range does not overlap with SMRAM ranges via
> VariableSmmIsBufferOutsideSmmValid ().
> >
> > V4 Changes:
> >  [PATCH V3 7/9] MdeModulePkg/Variable: Add RT GetVariable() cache
> > support
> >  * Set
> gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache to
> FALSE
> >    by default in MdeModulePkg.dec.
> >
> >  * Added a new patch to set
> gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache
> >    to TRUE at the end of the patch series. This allows someone to bisect an
> issue at
> >    patch #7 or patch #8 in the series with no change in variable caching
> behavior. The
> >    runtime cache variable logic would be applied explicitly in V4 patch #10.
> 
> I gave my R-b for the OvmfPkg patch in the v4 posting:
> 
> https://edk2.groups.io/g/devel/message/48979
> 
> (alternative link:
> 
> http://mid.mail-archive.com/b89583ed-06ef-ccd2-2e29-
> d054f581ea6a@redhat.com
> )
> 
> In the v5 posting -- assuming you had not changed that specific OvmfPkg
> patch, relative to v4 -- you should have picked up my R-b, and carried it
> forward ever since (to the present v7). Basically, do a git-rebase, select the
> "reword" action for the patch, then cut&paste my R-b from my
> v4 review email to the bottom of the commit message. Then every further
> posting will contain it.
> 
> If there *have* been changes to the patch, relative to v4, then it's indeed
> right to drop (or simply not pick up) my R-b. FWIW, the changelog above
> does not suggest the particular patch has seen any changes since v4.
> 
> Thanks!
> Laszlo
> 
> >
> > V3 Changes:
> >  [PATCH V2 1/9] MdeModulePkg/Variable: Consolidate common parsing
> > functions
> >  * Removed GUIDs added to VariableStandaloneMm.inf that are not
> required.
> >  * Added more details to the commit message describing the criteria of
> >    moving the chosen functions to VariableParsing.c.
> >
> >  [PATCH V2 2/9] MdeModulePkg/Variable: Parameterize
> > GetNextVariableEx() store list
> >  * RenamedGetNextVariableEx () to
> > VariableServiceGetNextVariableInternal ()
> >  * Updated comments in VariableServiceGetNextVariableInternal () to
> refer to
> >    "FindVariablEx ()" instead of "FindVariable ()" since FindVariableEx ()
> >    is not used in the function.
> >
> >  [PATCH V2 3/9] MdeModulePkg/Variable: Parameterize
> > VARIABLE_INFO_ENTRY buffer
> >  * Updated the commit message to clarify the message "structure can be
> updated
> >    outside the fixed global variable".
> >
> >  [edk2-devel] [PATCH V2 4/9] MdeModulePkg/Variable: Add local auth
> > status in VariableParsing
> >  * Remove the function InitVariableParsing ()
> >  * Remove the mAuthFormat global variable and instead add a BOOLEAN
> parameter
> >    to all functions that require variable authentication information  to
> >    indicate if authenticated variables are used.
> >    * This allows the authenticated variable status to be tracked in one place
> in
> >      each variable driver in the SMM variable solution
> (VariableSmmRuntimeDxe
> >      and VariableSmm).
> >
> >  [edk2-devel] [PATCH V2 5/9] MdeModulePkg/Variable: Add a file for NV
> > variable functions
> >  * Added the following non-volatile related functions to
> VariableNonVolatile.c
> >    from Variable.c:
> >    * InitRealNonVolatileVariableStore ()
> >    * InitEmuNonVolatileVariableStore ()
> >    * InitNonVolatileVariableStore ()
> >
> >  [edk2-devel] [PATCH V2 7/9] MdeModulePkg/Variable: Add RT
> > GetVariable() cache support
> >  * Added a FeaturePCD to control enabling the runtime variable cache -
> >    gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache.
> >  * Removed usage of the TimerLib and the wait to acquire
> >    mVariableRuntimeCacheReadLock. Can rely on the UEFI specification
> >    restrictions on Runtime Services callers.
> >  * Removed the EFIAPI keyword from internal functions.
> >  * Removed PCDs in VariableSmmRuntimeDxe.inf not required.
> >  * Removed the HobVariableBackupBase variable no longer required.
> >  * Renamed SynchronizeRuntimeVariableCacheEx () to better reflect
> usage.
> >  * Renamed functions in VariableRuntimeCache.c to better reflect usage.
> >  * Introduced a local variable in
> FlushPendingRuntimeVariableCacheUpdates ()
> >    to reduce duplication of
> >    mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.
> >  * Corrected the macro used in SmmVariableHandler () to
> >
> SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT.
> >  * Remove usage of the
> EDKII_PI_SMM_COMMUNICATION_REGION_TABLE to acquire a
> >    CommBuffer from the EFI System Table and use the same runtime
> CommBuffer
> >    allocated for variable SMM communicate calls.
> >
> >  [PATCH V2 8/9] MdeModulePkg/Variable: Add RT GetNextVariableName()
> > cache support
> >  * Removed usage of the TimerLib and the wait to acquire
> >    mVariableRuntimeCacheReadLock. Can rely on the UEFI specification
> restrictions
> >    on Runtime Services callers.
> >
> >  * Added a new patch to disable
> gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache
> >    for all OvmfPkg package builds as requested by maintainer Laszlo Ersek.
> >
> > V2 Changes:
> >
> > Patch #1 in V1 both moved functions to VariableParsing.c and modified
> > some functionality in those functions. In V2, the functions are first
> > moved and then functionality is modified in subsequent patches. This
> > resulted in the following new patches in the V2 patch series:
> >
> >  1. MdeModulePkg/Variable: Parameterize GetNextVariableEx() store list
> > 2. MdeModulePkg/Variable: Parameterize VARIABLE_INFO_ENTRY buffer
> 3.
> > MdeModulePkg/Variable: Add local auth status in VariableParsing  4.
> > MdeModulePkg/Variable: Add a file for NV variable functions
> >
> > Apart from this refactor in the patches, no functionally impacting
> > changes were made.
> >
> > Overview
> > ---------
> > This patch series reduces SMM usage when using
> VariableSmmRuntimeDxe
> > with VariableSmm. It does so by eliminating SMM usage for runtime
> > service GetVariable () and GetNextVariableName () invocations. Most
> > UEFI variable usage in typical systems after the variable store is
> > initialized (e.g. manufacturing boots) is due to GetVariable ( ) and
> > GetNextVariableName () not SetVariable (). GetVariable () calls can
> > regularly exceed 100 per boot while SetVariable () calls typically
> > remain less than 10 per boot. By focusing on the common case, the
> > majority of overhead associated with SMM can be avoided while still
> > using existing and proven code for operations such as variable
> > authentication that require an isolated execution environment.
> >
> >  * Advantage: Reduces overall system SMM usage
> >  * Disadvantage: Requires more Runtime data memory usage
> >
> > The runtime cache behavior described for this patch series is enabled
> > by default but can be disabled with a new FeaturePCD added to
> MdeModulePkg.dec:
> >   gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache
> >
> > The reaminder of this blurb describes the changes and behavior when
> > the PCD is set to TRUE.
> >
> > Initial Performance Observations
> > ---------------------------------
> >  * With these proposed changes, an Intel Atom based SoC saw GetVariable
> ( )
> >    time for an existing variable reduce from ~220us to ~5us.
> >
> > Major Changes
> > --------------
> >  1. Two UEFI variable caches will be maintained.
> >      a. "Runtime Cache" - Maintained in VariableSmmRuntimeDxe. Used to
> serve
> >          runtime service GetVariable () and GetNextVariableName () callers.
> >      b. "SMM cache" - Maintained in VariableSmm to service SMM
> GetVariable ()
> >          and GetNextVariableName () callers.
> >          i. A cache in SMRAM is retained so SMM modules do not operate on
> data
> >             outside SMRAM.
> >  2. A new UEFI variable read and write flow will be used as described below.
> >
> > At any given time, the two caches would be coherent. On a variable
> > write, the runtime cache is only updated after validation in SMM and,
> > in the case of a non-volatile UEFI variable, the variable must also be
> > successfully written to non-volatile storage.
> >
> > Prior RFC Feedback Addressed
> > -----------------------------
> > RFC sent Sept. 5, 2019: https://edk2.groups.io/g/devel/message/46939
> >
> > 1. UEFI variable data retrieval from a ring 0 buffer
> >
> >    A common concern with this proposed set of changes is the potential
> security
> >    threat presented by serving runtime services callers from a ring 0 memory
> >    buffer of EfiRuntimeServicesData type. The conclusion was that this
> change
> >    does not fundamentally alter the attack surface. The UEFI variable
> Runtime
> >    Services are invoked from ring 0 and the data already travels through ring
> >    0 buffers (such as the SMM communicate buffer) to reach the caller. Even
> >    today if ring 0 is assumed to be malicious, the malicious code may keep
> one
> >    AP in a loop to monitor the communication data, when the BSP gets an
> >    (authenticated) variable. When the communication buffer is updated and
> the
> >    status is set to EFI_SUCCESS, the AP may modify the communication
> buffer
> >    contents such the tampered data is returned to the BSP caller. Or an
> >    interrupt handler on the BSP may alter the communication buffer
> contents
> >    before the data is returned to the caller. In summary, this was not found
> to
> >    introduce any attack not possible today.
> >
> > 2. VarCheckLib impact
> >
> >    VarCheckLib plays a role in SetVariable () calls. This patch series only
> >    changes GetVariable () behavior. Therefore, VarCheckLib is expected to
> >    have no impact due to these changes.
> >
> > Testing Performed
> > ------------------
> > This code was tested with the master branch of edk2 on an Intel Kaby
> > Lake U and Intel Whiskey Lake U reference validation platform. The set
> > of tests performed included:
> >
> > 1.  Boot from S5 to Windows 10 OS with SMM variables enabled and
> >     the variable runtime cache enabled.
> > 2.  Boot from S5 to Ubuntu 18.04.1 LTS with SMM variable enabled
> >     and the variable runtime cache enabled.
> > 3.  Boot from S5 to Windows 10 OS with SMM variables enabled and
> >     the variable runtime cache disabled.
> > 4.  Boot from S5 to Ubuntu 18.04.1 LTS with SMM variable enabled
> >     and the variable runtime cache disabled.
> > 5.  Boot from S5 to EFI shell with DXE variables enabled.
> >     (commit 2de1f611be broke OvmfPkgIa32X64 boot regardless of
> >      this patch series; testing without this commit was successful) 6.
> > Dump UEFI variable store at shell with dmpstore to verify contents.
> > 7.  Dump NvStorage FV from SPI flash after boot to verify contents written.
> > 8.  Dump UEFI variable statistics with VariableInfo at shell.
> > 9.  Boot with emulated variables enabled.
> > 10. Cycles of adding and deleting a UEFI variable to verify cache
> correctness.
> > 11. Set OsIndications to stop at FW UI to verify cache load of non-volatile
> >     contents.
> >
> > Why Keep SMM on Variable Writes
> > --------------------------------
> >  * SMM provides a ubiquitous isolated execution environment in x86 for
> >    authenticated UEFI variables.
> >  * BIOS region SPI flash write restrictions to SMM in platforms today can
> >    be retained.
> >
> > Today's UEFI Variable Cache (for reference)
> > --------------------------------------------
> >  * Maintained in SMRAM via VariableSmm.
> >  * A "write-through" cache of variable data in the form of a UEFI variable
> >    store.
> >  * Non-volatile and volatile variables are maintained in separate buffers
> >   (variable stores).
> >
> > Runtime & SMM Cache Coherency
> > ------------------------------
> > The non-volatile cache should always accurately reflect non-volatile
> > storage contents (done today) and the "SMM cache" and "Runtime cache"
> > should always be coherent on access. The runtime cache is updated by
> VariableSmm.
> >
> > Updating both caches from within a SMM SetVariable () operation is
> > fairly straightforward but a race condition can occur if an SMI occurs
> > during the execution of runtime code reading from the runtime cache.
> > To handle this case, a runtime cache read lock is introduced that
> > explicitly moves pending updates from SMM to the runtime cache if an
> > SMM update occurs while the runtime cache is locked. Note that it is
> > not expected a Runtime services call will interrupt SMM processing since all
> CPU cores rendezvous in SMM.
> >
> > New Key Elements for Coherence
> > -------------------------------
> > Runtime DXE (VariableSmmRuntimeDxe)
> >  1. RuntimeCacheReadLock - A global lock used to lock read access to the
> >                            runtime cache.
> >  2. RuntimeCachePendingUpdate - A global flag used to notify runtime code
> of a
> >                                 pending cache update in SMM.
> >
> > SMM (VariableSmm)
> >  1. FlushRuntimeCachePendingUpdate SMI - A SW SMI handler that
> synchronizes
> >                                          the runtime cache buffer with the SMM
> >                                          cache buffer.
> >
> > Proposed Runtime DXE Read Flow
> > -------------------------------
> >  1. Acquire RuntimeCacheReadLock
> >  2. If RuntimeCachePendingUpdate flag (rare) is set then:
> >      2.a. Trigger FlushRuntimeCachePendingUpdate SMI
> >      2.b. Verify RuntimeCachePendingUpdate flag is cleared  3. Perform
> > read from RuntimeCache  4. Release RuntimeCacheReadLock
> >
> > Proposed FlushRuntimeCachePendingUpdate SMI
> > --------------------------------------------
> >  1. If RuntimeCachePendingUpdate flag is not set:
> >      1.a. Return
> >  2. Copy the data at RuntimeCachePendingOffset of
> RuntimeCachePendingLength to
> >     RuntimeCache
> >  3. Clear the RuntimeCachePendingUpdate flag
> >
> > Proposed SMM Write Flow
> > ------------------------
> >  1. Perform variable authentication and non-volatile write. If either fail,
> >     return an error to the caller.
> >  2. If RuntimeCacheReadLock is set then:
> >      2.a. Set RuntimeCachePendingUpdate flag
> >      2.b. Update RuntimeCachePendingOffset and
> RuntimeCachePendingLength to
> >           cover the a superset of the pending chunk (for simplicity, the
> >           entire variable store is currently synchronized).
> > 3. Else:
> >      3.a. Update RuntimeCache
> > 4. Update SmmCache
> >      - Note: RT read cannot occur during SMI processing since all cores are
> >              locked in SMM.
> >
> > Cc: Dandan Bi <dandan.bi@intel.com>
> > Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
> > Cc: Eric Dong <eric.dong@intel.com>
> > Cc: Laszlo Ersek <lersek@redhat.com>
> > Cc: Liming Gao <liming.gao@intel.com>
> > Cc: Michael D Kinney <michael.d.kinney@intel.com>
> > Cc: Ray Ni <ray.ni@intel.com>
> > Cc: Jian J Wang <jian.j.wang@intel.com>
> > Cc: Hao A Wu <hao.a.wu@intel.com>
> > Cc: Jiewen Yao <jiewen.yao@intel.com>
> > Signed-off-by: Michael Kubacki <michael.a.kubacki@intel.com>
> >
> > Michael Kubacki (10):
> >   MdeModulePkg/Variable: Consolidate common parsing functions
> >   MdeModulePkg/Variable: Parameterize GetNextVariableInternal () stores
> >   MdeModulePkg/Variable: Parameterize VARIABLE_INFO_ENTRY buffer
> >   MdeModulePkg/Variable: Parameterize auth status in VariableParsing
> >   MdeModulePkg/Variable: Add a file for NV variable functions
> >   MdeModulePkg VariableInfo: Always consider RT DXE and SMM stats
> >   MdeModulePkg/Variable: Add RT GetVariable() cache support
> >   MdeModulePkg/Variable: Add RT GetNextVariableName() cache support
> >   OvmfPkg: Disable variable runtime cache
> >   MdeModulePkg: Enable variable runtime cache by default
> >
> >  MdeModulePkg/MdeModulePkg.dec                                        |   12 +
> >  OvmfPkg/OvmfPkgIa32.dsc                                              |    1 +
> >  OvmfPkg/OvmfPkgIa32X64.dsc                                           |    1 +
> >  OvmfPkg/OvmfPkgX64.dsc                                               |    1 +
> >  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
> |    6 +
> >  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf           |
> 6 +
> >
> MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.i
> nf |   18 +-
> >
> MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf
> |    6 +
> >  MdeModulePkg/Include/Guid/SmmVariableCommon.h                        |   29
> +-
> >  MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h                |  151
> +--
> >  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.h
> |   67 +
> >  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h         |
> 347 +++++
> >
> MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.h
> |   51 +
> >  MdeModulePkg/Application/VariableInfo/VariableInfo.c                 |   37 +-
> >  MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c                | 1373
> ++++----------------
> >  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c           |
> 24 +-
> >  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.c
> |  334 +++++
> >  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c         |
> 786 +++++++++++
> >  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.c
> |  153 +++
> >  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c             |
> 195 ++-
> >
> MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.
> c   |  655 +++++++++-
> >  21 files changed, 2924 insertions(+), 1329 deletions(-)  create mode
> > 100644
> > MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.h
> >  create mode 100644
> > MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h
> >  create mode 100644
> > MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.h
> >  create mode 100644
> > MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.c
> >  create mode 100644
> > MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c
> >  create mode 100644
> > MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.c
> >


^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH V7 07/10] MdeModulePkg/Variable: Add RT GetVariable() cache support
  2019-11-01 17:34 ` [PATCH V7 07/10] MdeModulePkg/Variable: Add RT GetVariable() cache support Kubacki, Michael A
@ 2019-11-02  1:36   ` Wang, Jian J
  0 siblings, 0 replies; 14+ messages in thread
From: Wang, Jian J @ 2019-11-02  1:36 UTC (permalink / raw)
  To: Kubacki, Michael A, devel@edk2.groups.io
  Cc: Bi, Dandan, Ard Biesheuvel, Dong, Eric, Laszlo Ersek, Gao, Liming,
	Kinney, Michael D, Ni, Ray, Wu, Hao A, Yao, Jiewen

I've given R-b for other patches in this series. I just give R-b this one which is only changed
in v7.

Reviewed-by: Jian J Wang <jian.j.wang@intel.com>

Regards,
Jian

> -----Original Message-----
> From: Kubacki, Michael A <michael.a.kubacki@intel.com>
> Sent: Saturday, November 02, 2019 1:35 AM
> To: devel@edk2.groups.io
> Cc: Bi, Dandan <dandan.bi@intel.com>; Ard Biesheuvel
> <ard.biesheuvel@linaro.org>; Dong, Eric <eric.dong@intel.com>; Laszlo Ersek
> <lersek@redhat.com>; Gao, Liming <liming.gao@intel.com>; Kinney, Michael D
> <michael.d.kinney@intel.com>; Ni, Ray <ray.ni@intel.com>; Wang, Jian J
> <jian.j.wang@intel.com>; Wu, Hao A <hao.a.wu@intel.com>; Yao, Jiewen
> <jiewen.yao@intel.com>
> Subject: [PATCH V7 07/10] MdeModulePkg/Variable: Add RT GetVariable() cache
> support
> 
> REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2220
> 
> This change reduces SMIs for GetVariable () by maintaining a
> UEFI variable cache in Runtime DXE in addition to the pre-
> existing cache in SMRAM. When the Runtime Service GetVariable()
> is invoked, a Runtime DXE cache is used instead of triggering an
> SMI to VariableSmm. This can improve overall system performance
> by servicing variable read requests without rendezvousing all
> cores into SMM.
> 
> The runtime cache  can be disabled with by setting the FeaturePCD
> gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache
> to FALSE. If the PCD is set to FALSE, the runtime cache will not be
> used and an SMI will be triggered for Runtime Service
> GetVariable () and GetNextVariableName () invocations.
> 
> The following are important points regarding the behavior of the
> variable drivers when the variable runtime cache is enabled.
> 
> 1. All of the non-volatile storage contents are loaded into the
>    cache upon driver load. This one time load operation from storage
>    is preferred as opposed to building the cache on demand. An on-
>    demand cache would require a fallback SMI to load data into the
>    cache as variables are requested.
> 
> 2. SetVariable () requests will continue to always trigger an SMI.
>    This occurs regardless of whether the variable is volatile or
>    non-volatile.
> 
> 3. Both volatile and non-volatile variables are cached in a runtime
>    buffer. As is the case in the current EDK II variable driver, they
>    continue to be cached in separate buffers.
> 
> 4. The cache in Runtime DXE and SMM are intended to be exact copies
>    of one another. All SMM variable accesses only return data from the
>    SMM cache. The runtime caches are only updated after the variable I/O
>    operation is successful in SMM. The runtime caches are only updated
>    from SMM.
> 
> 5. Synchronization mechanisms are in place to ensure the runtime cache
>    content integrity with the SMM cache. These may result in updates to
>    runtime cache that are the same in content but different in offset and
>    size from updates to the SMM cache.
> 
> When using SMM variables with runtime cache enabled, two caches will now
> be present.
> 1. "Runtime Cache" - Maintained in VariableSmmRuntimeDxe. Used to service
>    Runtime Services GetVariable () and GetNextVariableName () callers.
> 2. "SMM Cache" - Maintained in VariableSmm to service SMM GetVariable ()
>    and GetNextVariableName () callers.
>    a. This cache is retained so SMM modules do not operate on data outside
>       SMRAM.
> 
> Because a race condition can occur if an SMI occurs during the execution
> of runtime code reading from the runtime cache, a runtime cache read lock
> is introduced that explicitly moves pending updates from SMM to the runtime
> cache if an SMM update occurs while the runtime cache is locked. Note that
> it is not expected a Runtime services call will interrupt SMM processing
> since all CPU cores rendezvous in SMM.
> 
> It is possible to view UEFI variable read and write statistics by setting
> the gEfiMdeModulePkgTokenSpaceGuid.PcdVariableCollectStatistics FeaturePcd
> to TRUE and using the VariableInfo UEFI application in MdeModulePkg to dump
> variable statistics to the console. By doing so, a user can view the number
> of GetVariable () hits from the Runtime DXE variable driver (Runtime Cache
> hits) and the SMM variable driver (SMM Cache hits). SMM Cache hits for
> GetVariable () will occur when SMM modules invoke GetVariable ().
> 
> Cc: Dandan Bi <dandan.bi@intel.com>
> Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
> Cc: Eric Dong <eric.dong@intel.com>
> Cc: Laszlo Ersek <lersek@redhat.com>
> Cc: Liming Gao <liming.gao@intel.com>
> Cc: Michael D Kinney <michael.d.kinney@intel.com>
> Cc: Ray Ni <ray.ni@intel.com>
> Cc: Jian J Wang <jian.j.wang@intel.com>
> Cc: Hao A Wu <hao.a.wu@intel.com>
> Cc: Jiewen Yao <jiewen.yao@intel.com>
> Signed-off-by: Michael Kubacki <michael.a.kubacki@intel.com>
> ---
>  MdeModulePkg/MdeModulePkg.dec                                        |  12 +
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf    |   2
> +
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf           |   2 +
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf |
> 18 +-
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf  |
> 2 +
>  MdeModulePkg/Include/Guid/SmmVariableCommon.h                        |  29 +-
>  MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h                |  32 +-
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.h    |
> 51 ++
>  MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c                |  50 +-
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.c    |
> 153 ++++++
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c             | 189
> +++++++-
>  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c   |
> 512 +++++++++++++++++++-
>  12 files changed, 1011 insertions(+), 41 deletions(-)
> 
> diff --git a/MdeModulePkg/MdeModulePkg.dec
> b/MdeModulePkg/MdeModulePkg.dec
> index d6bac974da..3ef8fe7644 100644
> --- a/MdeModulePkg/MdeModulePkg.dec
> +++ b/MdeModulePkg/MdeModulePkg.dec
> @@ -641,6 +641,18 @@
>    # @Prompt Enable Device Path From Text support.
> 
> gEfiMdeModulePkgTokenSpaceGuid.PcdDevicePathSupportDevicePathFromText
> |TRUE|BOOLEAN|0x00010038
> 
> +  ## Indicates if the UEFI variable runtime cache should be enabled.
> +  #  This setting only applies if SMM variables are enabled. When enabled, all
> variable
> +  #  data for Runtime Service GetVariable () and GetNextVariableName () calls is
> retrieved
> +  #  from a runtime data buffer referred to as the "runtime cache". An SMI is not
> triggered
> +  #  at all for these requests. Variables writes still trigger an SMI. This can
> greatly
> +  #  reduce overall system SMM usage as most boots tend to issue far more
> variable reads
> +  #  than writes.<BR><BR>
> +  #   TRUE  - The UEFI variable runtime cache is enabled.<BR>
> +  #   FALSE - The UEFI variable runtime cache is disabled.<BR>
> +  # @Prompt Enable the UEFI variable runtime cache.
> +
> gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE|B
> OOLEAN|0x00010039
> +
>    ## Indicates if the statistics about variable usage will be collected. This
> information is
>    #  stored as a vendor configuration table into the EFI system table.
>    #  Set this PCD to TRUE to use VariableInfo application in
> MdeModulePkg\Application directory to get
> diff --git
> a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
> b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
> index 08a5490787..ceea5d1ff9 100644
> --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
> +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
> @@ -40,6 +40,8 @@
>    VariableNonVolatile.h
>    VariableParsing.c
>    VariableParsing.h
> +  VariableRuntimeCache.c
> +  VariableRuntimeCache.h
>    PrivilegePolymorphic.h
>    Measurement.c
>    TcgMorLockDxe.c
> diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf
> b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf
> index 6dc2721b81..bc3033588d 100644
> --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf
> +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf
> @@ -49,6 +49,8 @@
>    VariableNonVolatile.h
>    VariableParsing.c
>    VariableParsing.h
> +  VariableRuntimeCache.c
> +  VariableRuntimeCache.h
>    VarCheck.c
>    Variable.h
>    PrivilegePolymorphic.h
> diff --git
> a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf
> b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf
> index 14894e6f13..a250533a53 100644
> ---
> a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf
> +++
> b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf
> @@ -13,7 +13,7 @@
>  #  may not be modified without authorization. If platform fails to protect these
> resources,
>  #  the authentication service provided in this driver will be broken, and the
> behavior is undefined.
>  #
> -# Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.<BR>
> +# Copyright (c) 2010 - 2019, Intel Corporation. All rights reserved.<BR>
>  # SPDX-License-Identifier: BSD-2-Clause-Patent
>  #
>  ##
> @@ -39,6 +39,8 @@
>    VariableSmmRuntimeDxe.c
>    PrivilegePolymorphic.h
>    Measurement.c
> +  VariableParsing.c
> +  VariableParsing.h
> 
>  [Packages]
>    MdePkg/MdePkg.dec
> @@ -65,7 +67,21 @@
>    gEdkiiVariableLockProtocolGuid                ## PRODUCES
>    gEdkiiVarCheckProtocolGuid                    ## PRODUCES
> 
> +[FeaturePcd]
> +  gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache
> ## CONSUMES
> +  gEfiMdeModulePkgTokenSpaceGuid.PcdVariableCollectStatistics            ##
> CONSUMES
> +
>  [Guids]
> +  ## PRODUCES             ## GUID # Signature of Variable store header
> +  ## CONSUMES             ## GUID # Signature of Variable store header
> +  ## SOMETIMES_PRODUCES   ## SystemTable
> +  gEfiAuthenticatedVariableGuid
> +
> +  ## PRODUCES             ## GUID # Signature of Variable store header
> +  ## CONSUMES             ## GUID # Signature of Variable store header
> +  ## SOMETIMES_PRODUCES   ## SystemTable
> +  gEfiVariableGuid
> +
>    gEfiEventVirtualAddressChangeGuid             ## CONSUMES ## Event
>    gEfiEventExitBootServicesGuid                 ## CONSUMES ## Event
>    ## CONSUMES ## GUID # Locate protocol
> diff --git
> a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf
> b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf
> index f8a3742959..6e17f6cdf5 100644
> ---
> a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf
> +++
> b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf
> @@ -49,6 +49,8 @@
>    VariableNonVolatile.h
>    VariableParsing.c
>    VariableParsing.h
> +  VariableRuntimeCache.c
> +  VariableRuntimeCache.h
>    VarCheck.c
>    Variable.h
>    PrivilegePolymorphic.h
> diff --git a/MdeModulePkg/Include/Guid/SmmVariableCommon.h
> b/MdeModulePkg/Include/Guid/SmmVariableCommon.h
> index c527a59891..ceef44dfd2 100644
> --- a/MdeModulePkg/Include/Guid/SmmVariableCommon.h
> +++ b/MdeModulePkg/Include/Guid/SmmVariableCommon.h
> @@ -1,7 +1,7 @@
>  /** @file
>    The file defined some common structures used for communicating between
> SMM variable module and SMM variable wrapper module.
> 
> -Copyright (c) 2011 - 2015, Intel Corporation. All rights reserved.<BR>
> +Copyright (c) 2011 - 2019, Intel Corporation. All rights reserved.<BR>
>  SPDX-License-Identifier: BSD-2-Clause-Patent
> 
>  **/
> @@ -9,6 +9,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
>  #ifndef _SMM_VARIABLE_COMMON_H_
>  #define _SMM_VARIABLE_COMMON_H_
> 
> +#include <Guid/VariableFormat.h>
>  #include <Protocol/VarCheck.h>
> 
>  #define EFI_SMM_VARIABLE_WRITE_GUID \
> @@ -66,6 +67,16 @@ typedef struct {
>  #define SMM_VARIABLE_FUNCTION_VAR_CHECK_VARIABLE_PROPERTY_GET
> 10
> 
>  #define SMM_VARIABLE_FUNCTION_GET_PAYLOAD_SIZE        11
> +//
> +// The payload for this function is
> SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT
> +//
> +#define
> SMM_VARIABLE_FUNCTION_INIT_RUNTIME_VARIABLE_CACHE_CONTEXT   12
> +
> +#define SMM_VARIABLE_FUNCTION_SYNC_RUNTIME_CACHE                    13
> +//
> +// The payload for this function is
> SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO
> +//
> +#define SMM_VARIABLE_FUNCTION_GET_RUNTIME_CACHE_INFO                14
> 
>  ///
>  /// Size of SMM communicate header, without including the payload.
> @@ -120,4 +131,20 @@ typedef struct {
>    UINTN                         VariablePayloadSize;
>  } SMM_VARIABLE_COMMUNICATE_GET_PAYLOAD_SIZE;
> 
> +typedef struct {
> +  BOOLEAN                 *ReadLock;
> +  BOOLEAN                 *PendingUpdate;
> +  BOOLEAN                 *HobFlushComplete;
> +  VARIABLE_STORE_HEADER   *RuntimeHobCache;
> +  VARIABLE_STORE_HEADER   *RuntimeNvCache;
> +  VARIABLE_STORE_HEADER   *RuntimeVolatileCache;
> +} SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT;
> +
> +typedef struct {
> +  UINTN                   TotalHobStorageSize;
> +  UINTN                   TotalNvStorageSize;
> +  UINTN                   TotalVolatileStorageSize;
> +  BOOLEAN                 AuthenticatedVariableUsage;
> +} SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO;
> +
>  #endif // _SMM_VARIABLE_COMMON_H_
> diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h
> b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h
> index fb574b2e32..0b2bb6ae66 100644
> --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h
> +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h
> @@ -64,6 +64,21 @@ typedef enum {
>    VariableStoreTypeMax
>  } VARIABLE_STORE_TYPE;
> 
> +typedef struct {
> +  UINT32                  PendingUpdateOffset;
> +  UINT32                  PendingUpdateLength;
> +  VARIABLE_STORE_HEADER   *Store;
> +} VARIABLE_RUNTIME_CACHE;
> +
> +typedef struct {
> +  BOOLEAN                 *ReadLock;
> +  BOOLEAN                 *PendingUpdate;
> +  BOOLEAN                 *HobFlushComplete;
> +  VARIABLE_RUNTIME_CACHE  VariableRuntimeHobCache;
> +  VARIABLE_RUNTIME_CACHE  VariableRuntimeNvCache;
> +  VARIABLE_RUNTIME_CACHE  VariableRuntimeVolatileCache;
> +} VARIABLE_RUNTIME_CACHE_CONTEXT;
> +
>  typedef struct {
>    VARIABLE_HEADER *CurrPtr;
>    //
> @@ -79,14 +94,15 @@ typedef struct {
>  } VARIABLE_POINTER_TRACK;
> 
>  typedef struct {
> -  EFI_PHYSICAL_ADDRESS  HobVariableBase;
> -  EFI_PHYSICAL_ADDRESS  VolatileVariableBase;
> -  EFI_PHYSICAL_ADDRESS  NonVolatileVariableBase;
> -  EFI_LOCK              VariableServicesLock;
> -  UINT32                ReentrantState;
> -  BOOLEAN               AuthFormat;
> -  BOOLEAN               AuthSupport;
> -  BOOLEAN               EmuNvMode;
> +  EFI_PHYSICAL_ADDRESS            HobVariableBase;
> +  EFI_PHYSICAL_ADDRESS            VolatileVariableBase;
> +  EFI_PHYSICAL_ADDRESS            NonVolatileVariableBase;
> +  VARIABLE_RUNTIME_CACHE_CONTEXT  VariableRuntimeCacheContext;
> +  EFI_LOCK                        VariableServicesLock;
> +  UINT32                          ReentrantState;
> +  BOOLEAN                         AuthFormat;
> +  BOOLEAN                         AuthSupport;
> +  BOOLEAN                         EmuNvMode;
>  } VARIABLE_GLOBAL;
> 
>  typedef struct {
> diff --git
> a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.h
> b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.h
> new file mode 100644
> index 0000000000..f9804a1d69
> --- /dev/null
> +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.h
> @@ -0,0 +1,51 @@
> +/** @file
> +  The common variable volatile store routines shared by the DXE_RUNTIME
> variable
> +  module and the DXE_SMM variable module.
> +
> +Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
> +SPDX-License-Identifier: BSD-2-Clause-Patent
> +
> +**/
> +
> +#ifndef _VARIABLE_RUNTIME_CACHE_H_
> +#define _VARIABLE_RUNTIME_CACHE_H_
> +
> +#include "Variable.h"
> +
> +/**
> +  Copies any pending updates to runtime variable caches.
> +
> +  @retval EFI_UNSUPPORTED         The volatile store to be updated is not
> initialized properly.
> +  @retval EFI_SUCCESS             The volatile store was updated successfully.
> +
> +**/
> +EFI_STATUS
> +FlushPendingRuntimeVariableCacheUpdates (
> +  VOID
> +  );
> +
> +/**
> +  Synchronizes the runtime variable caches with all pending updates outside
> runtime.
> +
> +  Ensures all conditions are met to maintain coherency for runtime cache
> updates. This function will attempt
> +  to write the given update (and any other pending updates) if the ReadLock is
> available. Otherwise, the
> +  update is added as a pending update for the given variable store and it will be
> flushed to the runtime cache
> +  at the next opportunity the ReadLock is available.
> +
> +  @param[in] VariableRuntimeCache Variable runtime cache structure for the
> runtime cache being synchronized.
> +  @param[in] Offset               Offset in bytes to apply the update.
> +  @param[in] Length               Length of data in bytes of the update.
> +
> +  @retval EFI_SUCCESS             The update was added as a pending update
> successfully. If the variable runtime
> +                                  cache ReadLock was available, the runtime cache was
> updated successfully.
> +  @retval EFI_UNSUPPORTED         The volatile store to be updated is not
> initialized properly.
> +
> +**/
> +EFI_STATUS
> +SynchronizeRuntimeVariableCache (
> +  IN  VARIABLE_RUNTIME_CACHE          *VariableRuntimeCache,
> +  IN  UINTN                           Offset,
> +  IN  UINTN                           Length
> +  );
> +
> +#endif
> diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
> b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
> index 0bd2f22e1a..29d6aca993 100644
> --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
> +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
> @@ -25,6 +25,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
>  #include "Variable.h"
>  #include "VariableNonVolatile.h"
>  #include "VariableParsing.h"
> +#include "VariableRuntimeCache.h"
> 
>  VARIABLE_MODULE_GLOBAL  *mVariableModuleGlobal;
> 
> @@ -332,6 +333,12 @@ RecordVarErrorFlag (
>        // Update the data in NV cache.
>        //
>        *VarErrFlag = TempFlag;
> +      Status =  SynchronizeRuntimeVariableCache (
> +                  &mVariableModuleGlobal-
> >VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeNvCache,
> +                  (UINTN) VarErrFlag - (UINTN) mNvVariableCache + (UINTN)
> mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
> +                  sizeof (TempFlag)
> +                  );
> +      ASSERT_EFI_ERROR (Status);
>      }
>    }
>  }
> @@ -766,12 +773,24 @@ Reclaim (
> 
>  Done:
>    if (IsVolatile || mVariableModuleGlobal->VariableGlobal.EmuNvMode) {
> +    Status =  SynchronizeRuntimeVariableCache (
> +                &mVariableModuleGlobal-
> >VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeVolatileCache,
> +                0,
> +                VariableStoreHeader->Size
> +                );
> +    ASSERT_EFI_ERROR (Status);
>      FreePool (ValidBuffer);
>    } else {
>      //
>      // For NV variable reclaim, we use mNvVariableCache as the buffer, so copy
> the data back.
>      //
> -    CopyMem (mNvVariableCache, (UINT8 *)(UINTN)VariableBase,
> VariableStoreHeader->Size);
> +    CopyMem (mNvVariableCache, (UINT8 *) (UINTN) VariableBase,
> VariableStoreHeader->Size);
> +    Status =  SynchronizeRuntimeVariableCache (
> +                &mVariableModuleGlobal-
> >VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeNvCache,
> +                0,
> +                VariableStoreHeader->Size
> +                );
> +    ASSERT_EFI_ERROR (Status);
>    }
> 
>    return Status;
> @@ -1614,6 +1633,7 @@ UpdateVariable (
>    VARIABLE_POINTER_TRACK              *Variable;
>    VARIABLE_POINTER_TRACK              NvVariable;
>    VARIABLE_STORE_HEADER               *VariableStoreHeader;
> +  VARIABLE_RUNTIME_CACHE              *VolatileCacheInstance;
>    UINT8                               *BufferForMerge;
>    UINTN                               MergedBufSize;
>    BOOLEAN                             DataReady;
> @@ -2275,6 +2295,23 @@ UpdateVariable (
>    }
> 
>  Done:
> +  if (!EFI_ERROR (Status)) {
> +    if (Variable->Volatile) {
> +      VolatileCacheInstance = &(mVariableModuleGlobal-
> >VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeVolatileCache);
> +    } else {
> +      VolatileCacheInstance = &(mVariableModuleGlobal-
> >VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeNvCache);
> +    }
> +
> +    if (VolatileCacheInstance->Store != NULL) {
> +      Status =  SynchronizeRuntimeVariableCache (
> +                  VolatileCacheInstance,
> +                  0,
> +                  VolatileCacheInstance->Store->Size
> +                  );
> +      ASSERT_EFI_ERROR (Status);
> +    }
> +  }
> +
>    return Status;
>  }
> 
> @@ -3200,6 +3237,14 @@ FlushHobVariableToFlash (
>          ErrorFlag = TRUE;
>        }
>      }
> +    if (mVariableModuleGlobal-
> >VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeHobCache.Stor
> e != NULL) {
> +      Status =  SynchronizeRuntimeVariableCache (
> +                  &mVariableModuleGlobal-
> >VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeHobCache,
> +                  0,
> +                  mVariableModuleGlobal-
> >VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeHobCache.Stor
> e->Size
> +                  );
> +      ASSERT_EFI_ERROR (Status);
> +    }
>      if (ErrorFlag) {
>        //
>        // We still have HOB variable(s) not flushed in flash.
> @@ -3210,6 +3255,9 @@ FlushHobVariableToFlash (
>        // All HOB variables have been flushed in flash.
>        //
>        DEBUG ((EFI_D_INFO, "Variable driver: all HOB variables have been flushed
> in flash.\n"));
> +      if (mVariableModuleGlobal-
> >VariableGlobal.VariableRuntimeCacheContext.HobFlushComplete != NULL) {
> +        *(mVariableModuleGlobal-
> >VariableGlobal.VariableRuntimeCacheContext.HobFlushComplete) = TRUE;
> +      }
>        if (!AtRuntime ()) {
>          FreePool ((VOID *) VariableStoreHeader);
>        }
> diff --git
> a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.c
> b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.c
> new file mode 100644
> index 0000000000..bc93cc07d2
> --- /dev/null
> +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.c
> @@ -0,0 +1,153 @@
> +/** @file
> +  Functions related to managing the UEFI variable runtime cache. This file
> should only include functions
> +  used by the SMM UEFI variable driver.
> +
> +  Caution: This module requires additional review when modified.
> +  This driver will have external input - variable data. They may be input in SMM
> mode.
> +  This external input must be validated carefully to avoid security issue like
> +  buffer overflow, integer overflow.
> +
> +Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
> +SPDX-License-Identifier: BSD-2-Clause-Patent
> +
> +**/
> +
> +#include "VariableParsing.h"
> +#include "VariableRuntimeCache.h"
> +
> +extern VARIABLE_MODULE_GLOBAL   *mVariableModuleGlobal;
> +extern VARIABLE_STORE_HEADER    *mNvVariableCache;
> +
> +/**
> +  Copies any pending updates to runtime variable caches.
> +
> +  @retval EFI_UNSUPPORTED         The volatile store to be updated is not
> initialized properly.
> +  @retval EFI_SUCCESS             The volatile store was updated successfully.
> +
> +**/
> +EFI_STATUS
> +FlushPendingRuntimeVariableCacheUpdates (
> +  VOID
> +  )
> +{
> +  VARIABLE_RUNTIME_CACHE_CONTEXT    *VariableRuntimeCacheContext;
> +
> +  VariableRuntimeCacheContext = &mVariableModuleGlobal-
> >VariableGlobal.VariableRuntimeCacheContext;
> +
> +  if (VariableRuntimeCacheContext->VariableRuntimeNvCache.Store == NULL
> ||
> +      VariableRuntimeCacheContext->VariableRuntimeVolatileCache.Store ==
> NULL ||
> +      VariableRuntimeCacheContext->PendingUpdate == NULL) {
> +    return EFI_UNSUPPORTED;
> +  }
> +
> +  if (*(VariableRuntimeCacheContext->PendingUpdate)) {
> +    if (VariableRuntimeCacheContext->VariableRuntimeHobCache.Store != NULL
> &&
> +        mVariableModuleGlobal->VariableGlobal.HobVariableBase > 0) {
> +      CopyMem (
> +        (VOID *) (
> +          ((UINT8 *) (UINTN) VariableRuntimeCacheContext-
> >VariableRuntimeHobCache.Store) +
> +          VariableRuntimeCacheContext-
> >VariableRuntimeHobCache.PendingUpdateOffset
> +          ),
> +        (VOID *) (
> +          ((UINT8 *) (UINTN) mVariableModuleGlobal-
> >VariableGlobal.HobVariableBase) +
> +          VariableRuntimeCacheContext-
> >VariableRuntimeHobCache.PendingUpdateOffset
> +          ),
> +        VariableRuntimeCacheContext-
> >VariableRuntimeHobCache.PendingUpdateLength
> +        );
> +      VariableRuntimeCacheContext-
> >VariableRuntimeHobCache.PendingUpdateLength = 0;
> +      VariableRuntimeCacheContext-
> >VariableRuntimeHobCache.PendingUpdateOffset = 0;
> +    }
> +
> +    CopyMem (
> +      (VOID *) (
> +        ((UINT8 *) (UINTN) VariableRuntimeCacheContext-
> >VariableRuntimeNvCache.Store) +
> +        VariableRuntimeCacheContext-
> >VariableRuntimeNvCache.PendingUpdateOffset
> +        ),
> +      (VOID *) (
> +        ((UINT8 *) (UINTN) mNvVariableCache) +
> +        VariableRuntimeCacheContext-
> >VariableRuntimeNvCache.PendingUpdateOffset
> +        ),
> +      VariableRuntimeCacheContext-
> >VariableRuntimeNvCache.PendingUpdateLength
> +      );
> +    VariableRuntimeCacheContext-
> >VariableRuntimeNvCache.PendingUpdateLength = 0;
> +    VariableRuntimeCacheContext-
> >VariableRuntimeNvCache.PendingUpdateOffset = 0;
> +
> +    CopyMem (
> +      (VOID *) (
> +        ((UINT8 *) (UINTN) VariableRuntimeCacheContext-
> >VariableRuntimeVolatileCache.Store) +
> +        VariableRuntimeCacheContext-
> >VariableRuntimeVolatileCache.PendingUpdateOffset
> +      ),
> +      (VOID *) (
> +        ((UINT8 *) (UINTN) mVariableModuleGlobal-
> >VariableGlobal.VolatileVariableBase) +
> +        VariableRuntimeCacheContext-
> >VariableRuntimeVolatileCache.PendingUpdateOffset
> +        ),
> +      VariableRuntimeCacheContext-
> >VariableRuntimeVolatileCache.PendingUpdateLength
> +      );
> +    VariableRuntimeCacheContext-
> >VariableRuntimeVolatileCache.PendingUpdateLength = 0;
> +    VariableRuntimeCacheContext-
> >VariableRuntimeVolatileCache.PendingUpdateOffset = 0;
> +    *(VariableRuntimeCacheContext->PendingUpdate) = FALSE;
> +  }
> +
> +  return EFI_SUCCESS;
> +}
> +
> +/**
> +  Synchronizes the runtime variable caches with all pending updates outside
> runtime.
> +
> +  Ensures all conditions are met to maintain coherency for runtime cache
> updates. This function will attempt
> +  to write the given update (and any other pending updates) if the ReadLock is
> available. Otherwise, the
> +  update is added as a pending update for the given variable store and it will be
> flushed to the runtime cache
> +  at the next opportunity the ReadLock is available.
> +
> +  @param[in] VariableRuntimeCache Variable runtime cache structure for the
> runtime cache being synchronized.
> +  @param[in] Offset               Offset in bytes to apply the update.
> +  @param[in] Length               Length of data in bytes of the update.
> +
> +  @retval EFI_SUCCESS             The update was added as a pending update
> successfully. If the variable runtime
> +                                  cache ReadLock was available, the runtime cache was
> updated successfully.
> +  @retval EFI_UNSUPPORTED         The volatile store to be updated is not
> initialized properly.
> +
> +**/
> +EFI_STATUS
> +SynchronizeRuntimeVariableCache (
> +  IN  VARIABLE_RUNTIME_CACHE          *VariableRuntimeCache,
> +  IN  UINTN                           Offset,
> +  IN  UINTN                           Length
> +  )
> +{
> +  if (VariableRuntimeCache == NULL) {
> +    return EFI_INVALID_PARAMETER;
> +  } else if (VariableRuntimeCache->Store == NULL) {
> +    // The runtime cache may not be active or allocated yet.
> +    // In either case, return EFI_SUCCESS instead of EFI_NOT_AVAILABLE_YET.
> +    return EFI_SUCCESS;
> +  }
> +
> +  if (mVariableModuleGlobal-
> >VariableGlobal.VariableRuntimeCacheContext.PendingUpdate == NULL ||
> +      mVariableModuleGlobal-
> >VariableGlobal.VariableRuntimeCacheContext.ReadLock == NULL) {
> +    return EFI_UNSUPPORTED;
> +  }
> +
> +  if (*(mVariableModuleGlobal-
> >VariableGlobal.VariableRuntimeCacheContext.PendingUpdate) &&
> +      VariableRuntimeCache->PendingUpdateLength > 0) {
> +    VariableRuntimeCache->PendingUpdateLength =
> +      (UINT32) (
> +        MAX (
> +          (UINTN) (VariableRuntimeCache->PendingUpdateOffset +
> VariableRuntimeCache->PendingUpdateLength),
> +          Offset + Length
> +        ) - MIN ((UINTN) VariableRuntimeCache->PendingUpdateOffset, Offset)
> +      );
> +    VariableRuntimeCache->PendingUpdateOffset =
> +      (UINT32) MIN ((UINTN) VariableRuntimeCache->PendingUpdateOffset,
> Offset);
> +  } else {
> +    VariableRuntimeCache->PendingUpdateLength = (UINT32) Length;
> +    VariableRuntimeCache->PendingUpdateOffset = (UINT32) Offset;
> +  }
> +  *(mVariableModuleGlobal-
> >VariableGlobal.VariableRuntimeCacheContext.PendingUpdate) = TRUE;
> +
> +  if (*(mVariableModuleGlobal-
> >VariableGlobal.VariableRuntimeCacheContext.ReadLock) == FALSE) {
> +    return FlushPendingRuntimeVariableCacheUpdates ();
> +  }
> +
> +  return EFI_SUCCESS;
> +}
> diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c
> b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c
> index 5e24bc4a62..caca5c3241 100644
> --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c
> +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c
> @@ -31,6 +31,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
>  #include <Guid/SmmVariableCommon.h>
>  #include "Variable.h"
>  #include "VariableParsing.h"
> +#include "VariableRuntimeCache.h"
> +
> +extern VARIABLE_STORE_HEADER                         *mNvVariableCache;
> 
>  BOOLEAN                                              mAtRuntime              = FALSE;
>  UINT8                                                *mVariableBufferPayload = NULL;
> @@ -451,25 +454,29 @@ SmmVariableGetStatistics (
>  EFI_STATUS
>  EFIAPI
>  SmmVariableHandler (
> -  IN     EFI_HANDLE                                DispatchHandle,
> -  IN     CONST VOID                                *RegisterContext,
> -  IN OUT VOID                                      *CommBuffer,
> -  IN OUT UINTN                                     *CommBufferSize
> +  IN     EFI_HANDLE                                       DispatchHandle,
> +  IN     CONST VOID                                       *RegisterContext,
> +  IN OUT VOID                                             *CommBuffer,
> +  IN OUT UINTN                                            *CommBufferSize
>    )
>  {
> -  EFI_STATUS                                       Status;
> -  SMM_VARIABLE_COMMUNICATE_HEADER
> *SmmVariableFunctionHeader;
> -  SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE
> *SmmVariableHeader;
> -  SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME
> *GetNextVariableName;
> -  SMM_VARIABLE_COMMUNICATE_QUERY_VARIABLE_INFO
> *QueryVariableInfo;
> -  SMM_VARIABLE_COMMUNICATE_GET_PAYLOAD_SIZE        *GetPayloadSize;
> -  VARIABLE_INFO_ENTRY                              *VariableInfo;
> -  SMM_VARIABLE_COMMUNICATE_LOCK_VARIABLE           *VariableToLock;
> -  SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY
> *CommVariableProperty;
> -  UINTN                                            InfoSize;
> -  UINTN                                            NameBufferSize;
> -  UINTN                                            CommBufferPayloadSize;
> -  UINTN                                            TempCommBufferSize;
> +  EFI_STATUS                                              Status;
> +  SMM_VARIABLE_COMMUNICATE_HEADER
> *SmmVariableFunctionHeader;
> +  SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE
> *SmmVariableHeader;
> +  SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME
> *GetNextVariableName;
> +  SMM_VARIABLE_COMMUNICATE_QUERY_VARIABLE_INFO
> *QueryVariableInfo;
> +  SMM_VARIABLE_COMMUNICATE_GET_PAYLOAD_SIZE
> *GetPayloadSize;
> +  SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT
> *RuntimeVariableCacheContext;
> +  SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO
> *GetRuntimeCacheInfo;
> +  SMM_VARIABLE_COMMUNICATE_LOCK_VARIABLE                  *VariableToLock;
> +  SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY
> *CommVariableProperty;
> +  VARIABLE_INFO_ENTRY                                     *VariableInfo;
> +  VARIABLE_RUNTIME_CACHE_CONTEXT                          *VariableCacheContext;
> +  VARIABLE_STORE_HEADER                                   *VariableCache;
> +  UINTN                                                   InfoSize;
> +  UINTN                                                   NameBufferSize;
> +  UINTN                                                   CommBufferPayloadSize;
> +  UINTN                                                   TempCommBufferSize;
> 
>    //
>    // If input is invalid, stop processing this SMI
> @@ -789,6 +796,154 @@ SmmVariableHandler (
>                   );
>        CopyMem (SmmVariableFunctionHeader->Data, mVariableBufferPayload,
> CommBufferPayloadSize);
>        break;
> +    case
> SMM_VARIABLE_FUNCTION_INIT_RUNTIME_VARIABLE_CACHE_CONTEXT:
> +      if (CommBufferPayloadSize < sizeof
> (SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT)) {
> +        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: SMM
> communication buffer size invalid!\n"));
> +        Status = EFI_ACCESS_DENIED;
> +        goto EXIT;
> +      }
> +      if (mEndOfDxe) {
> +        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Cannot init
> context after end of DXE!\n"));
> +        Status = EFI_ACCESS_DENIED;
> +        goto EXIT;
> +      }
> +
> +      //
> +      // Copy the input communicate buffer payload to the pre-allocated SMM
> variable payload buffer.
> +      //
> +      CopyMem (mVariableBufferPayload, SmmVariableFunctionHeader->Data,
> CommBufferPayloadSize);
> +      RuntimeVariableCacheContext =
> (SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT *)
> mVariableBufferPayload;
> +
> +      //
> +      // Verify required runtime cache buffers are provided.
> +      //
> +      if (RuntimeVariableCacheContext->RuntimeVolatileCache == NULL ||
> +          RuntimeVariableCacheContext->RuntimeNvCache == NULL ||
> +          RuntimeVariableCacheContext->PendingUpdate == NULL ||
> +          RuntimeVariableCacheContext->ReadLock == NULL ||
> +          RuntimeVariableCacheContext->HobFlushComplete == NULL) {
> +        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Required
> runtime cache buffer is NULL!\n"));
> +        Status = EFI_ACCESS_DENIED;
> +        goto EXIT;
> +      }
> +
> +      //
> +      // Verify minimum size requirements for the runtime variable store buffers.
> +      //
> +      if ((RuntimeVariableCacheContext->RuntimeHobCache != NULL &&
> +          RuntimeVariableCacheContext->RuntimeHobCache->Size < sizeof
> (VARIABLE_STORE_HEADER)) ||
> +          RuntimeVariableCacheContext->RuntimeVolatileCache->Size < sizeof
> (VARIABLE_STORE_HEADER) ||
> +          RuntimeVariableCacheContext->RuntimeNvCache->Size < sizeof
> (VARIABLE_STORE_HEADER)) {
> +        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: A runtime
> cache buffer size is invalid!\n"));
> +        Status = EFI_ACCESS_DENIED;
> +        goto EXIT;
> +      }
> +
> +      //
> +      // Verify runtime buffers do not overlap with SMRAM ranges.
> +      //
> +      if (RuntimeVariableCacheContext->RuntimeHobCache != NULL &&
> +          !VariableSmmIsBufferOutsideSmmValid (
> +            (UINTN) RuntimeVariableCacheContext->RuntimeHobCache,
> +            (UINTN) RuntimeVariableCacheContext->RuntimeHobCache->Size)) {
> +        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Runtime
> HOB cache buffer in SMRAM or overflow!\n"));
> +        Status = EFI_ACCESS_DENIED;
> +        goto EXIT;
> +      }
> +      if (!VariableSmmIsBufferOutsideSmmValid (
> +            (UINTN) RuntimeVariableCacheContext->RuntimeVolatileCache,
> +            (UINTN) RuntimeVariableCacheContext->RuntimeVolatileCache->Size)) {
> +        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Runtime
> volatile cache buffer in SMRAM or overflow!\n"));
> +        Status = EFI_ACCESS_DENIED;
> +        goto EXIT;
> +      }
> +      if (!VariableSmmIsBufferOutsideSmmValid (
> +            (UINTN) RuntimeVariableCacheContext->RuntimeNvCache,
> +            (UINTN) RuntimeVariableCacheContext->RuntimeNvCache->Size)) {
> +        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Runtime
> non-volatile cache buffer in SMRAM or overflow!\n"));
> +        Status = EFI_ACCESS_DENIED;
> +        goto EXIT;
> +      }
> +      if (!VariableSmmIsBufferOutsideSmmValid (
> +            (UINTN) RuntimeVariableCacheContext->PendingUpdate,
> +            sizeof (*(RuntimeVariableCacheContext->PendingUpdate)))) {
> +        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Runtime
> cache pending update buffer in SMRAM or overflow!\n"));
> +        Status = EFI_ACCESS_DENIED;
> +        goto EXIT;
> +      }
> +      if (!VariableSmmIsBufferOutsideSmmValid (
> +            (UINTN) RuntimeVariableCacheContext->ReadLock,
> +            sizeof (*(RuntimeVariableCacheContext->ReadLock)))) {
> +        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Runtime
> cache read lock buffer in SMRAM or overflow!\n"));
> +        Status = EFI_ACCESS_DENIED;
> +        goto EXIT;
> +      }
> +      if (!VariableSmmIsBufferOutsideSmmValid (
> +            (UINTN) RuntimeVariableCacheContext->HobFlushComplete,
> +            sizeof (*(RuntimeVariableCacheContext->HobFlushComplete)))) {
> +        DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Runtime
> cache HOB flush complete buffer in SMRAM or overflow!\n"));
> +        Status = EFI_ACCESS_DENIED;
> +        goto EXIT;
> +      }
> +
> +      VariableCacheContext = &mVariableModuleGlobal-
> >VariableGlobal.VariableRuntimeCacheContext;
> +      VariableCacheContext->VariableRuntimeHobCache.Store      =
> RuntimeVariableCacheContext->RuntimeHobCache;
> +      VariableCacheContext->VariableRuntimeVolatileCache.Store =
> RuntimeVariableCacheContext->RuntimeVolatileCache;
> +      VariableCacheContext->VariableRuntimeNvCache.Store       =
> RuntimeVariableCacheContext->RuntimeNvCache;
> +      VariableCacheContext->PendingUpdate                      =
> RuntimeVariableCacheContext->PendingUpdate;
> +      VariableCacheContext->ReadLock                           =
> RuntimeVariableCacheContext->ReadLock;
> +      VariableCacheContext->HobFlushComplete                   =
> RuntimeVariableCacheContext->HobFlushComplete;
> +
> +      // Set up the intial pending request since the RT cache needs to be in sync
> with SMM cache
> +      VariableCacheContext->VariableRuntimeHobCache.PendingUpdateOffset =
> 0;
> +      VariableCacheContext->VariableRuntimeHobCache.PendingUpdateLength =
> 0;
> +      if (mVariableModuleGlobal->VariableGlobal.HobVariableBase > 0 &&
> +          VariableCacheContext->VariableRuntimeHobCache.Store != NULL) {
> +        VariableCache = (VARIABLE_STORE_HEADER *) (UINTN)
> mVariableModuleGlobal->VariableGlobal.HobVariableBase;
> +        VariableCacheContext->VariableRuntimeHobCache.PendingUpdateLength
> = (UINT32) ((UINTN) GetEndPointer (VariableCache) - (UINTN) VariableCache);
> +        CopyGuid (&(VariableCacheContext->VariableRuntimeHobCache.Store-
> >Signature), &(VariableCache->Signature));
> +      }
> +      VariableCache = (VARIABLE_STORE_HEADER  *) (UINTN)
> mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
> +      VariableCacheContext-
> >VariableRuntimeVolatileCache.PendingUpdateOffset   = 0;
> +      VariableCacheContext-
> >VariableRuntimeVolatileCache.PendingUpdateLength   = (UINT32) ((UINTN)
> GetEndPointer (VariableCache) - (UINTN) VariableCache);
> +      CopyGuid (&(VariableCacheContext->VariableRuntimeVolatileCache.Store-
> >Signature), &(VariableCache->Signature));
> +
> +      VariableCache = (VARIABLE_STORE_HEADER  *) (UINTN) mNvVariableCache;
> +      VariableCacheContext->VariableRuntimeNvCache.PendingUpdateOffset = 0;
> +      VariableCacheContext->VariableRuntimeNvCache.PendingUpdateLength =
> (UINT32) ((UINTN) GetEndPointer (VariableCache) - (UINTN) VariableCache);
> +      CopyGuid (&(VariableCacheContext->VariableRuntimeNvCache.Store-
> >Signature), &(VariableCache->Signature));
> +
> +      *(VariableCacheContext->PendingUpdate) = TRUE;
> +      *(VariableCacheContext->ReadLock) = FALSE;
> +      *(VariableCacheContext->HobFlushComplete) = FALSE;
> +
> +      Status = EFI_SUCCESS;
> +      break;
> +    case SMM_VARIABLE_FUNCTION_SYNC_RUNTIME_CACHE:
> +      Status = FlushPendingRuntimeVariableCacheUpdates ();
> +      break;
> +    case SMM_VARIABLE_FUNCTION_GET_RUNTIME_CACHE_INFO:
> +      if (CommBufferPayloadSize < sizeof
> (SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO)) {
> +        DEBUG ((DEBUG_ERROR, "GetRuntimeCacheInfo: SMM communication
> buffer size invalid!\n"));
> +        return EFI_SUCCESS;
> +      }
> +      GetRuntimeCacheInfo =
> (SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO *)
> SmmVariableFunctionHeader->Data;
> +
> +      if (mVariableModuleGlobal->VariableGlobal.HobVariableBase > 0) {
> +        VariableCache = (VARIABLE_STORE_HEADER *) (UINTN)
> mVariableModuleGlobal->VariableGlobal.HobVariableBase;
> +        GetRuntimeCacheInfo->TotalHobStorageSize = VariableCache->Size;
> +      } else {
> +        GetRuntimeCacheInfo->TotalHobStorageSize = 0;
> +      }
> +
> +      VariableCache = (VARIABLE_STORE_HEADER  *) (UINTN)
> mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;
> +      GetRuntimeCacheInfo->TotalVolatileStorageSize = VariableCache->Size;
> +      VariableCache = (VARIABLE_STORE_HEADER  *) (UINTN) mNvVariableCache;
> +      GetRuntimeCacheInfo->TotalNvStorageSize = (UINTN) VariableCache->Size;
> +      GetRuntimeCacheInfo->AuthenticatedVariableUsage =
> mVariableModuleGlobal->VariableGlobal.AuthFormat;
> +
> +      Status = EFI_SUCCESS;
> +      break;
> 
>      default:
>        Status = EFI_UNSUPPORTED;
> diff --git
> a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c
> b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c
> index 0a1888e5ef..3dee05fded 100644
> ---
> a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c
> +++
> b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c
> @@ -13,7 +13,7 @@
> 
>    InitCommunicateBuffer() is really function to check the variable data size.
> 
> -Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.<BR>
> +Copyright (c) 2010 - 2019, Intel Corporation. All rights reserved.<BR>
>  SPDX-License-Identifier: BSD-2-Clause-Patent
> 
>  **/
> @@ -39,6 +39,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
>  #include <Guid/SmmVariableCommon.h>
> 
>  #include "PrivilegePolymorphic.h"
> +#include "VariableParsing.h"
> 
>  EFI_HANDLE                       mHandle                    = NULL;
>  EFI_SMM_VARIABLE_PROTOCOL       *mSmmVariable               = NULL;
> @@ -46,8 +47,19 @@ EFI_EVENT                        mVirtualAddressChangeEvent =
> NULL;
>  EFI_SMM_COMMUNICATION_PROTOCOL  *mSmmCommunication          = NULL;
>  UINT8                           *mVariableBuffer            = NULL;
>  UINT8                           *mVariableBufferPhysical    = NULL;
> +VARIABLE_INFO_ENTRY             *mVariableInfo              = NULL;
> +VARIABLE_STORE_HEADER           *mVariableRuntimeHobCacheBuffer           =
> NULL;
> +VARIABLE_STORE_HEADER           *mVariableRuntimeNvCacheBuffer            =
> NULL;
> +VARIABLE_STORE_HEADER           *mVariableRuntimeVolatileCacheBuffer      =
> NULL;
>  UINTN                            mVariableBufferSize;
> +UINTN                            mVariableRuntimeHobCacheBufferSize;
> +UINTN                            mVariableRuntimeNvCacheBufferSize;
> +UINTN                            mVariableRuntimeVolatileCacheBufferSize;
>  UINTN                            mVariableBufferPayloadSize;
> +BOOLEAN                          mVariableRuntimeCachePendingUpdate;
> +BOOLEAN                          mVariableRuntimeCacheReadLock;
> +BOOLEAN                          mVariableAuthFormat;
> +BOOLEAN                          mHobFlushComplete;
>  EFI_LOCK                         mVariableServicesLock;
>  EDKII_VARIABLE_LOCK_PROTOCOL     mVariableLock;
>  EDKII_VAR_CHECK_PROTOCOL         mVarCheck;
> @@ -107,6 +119,72 @@ ReleaseLockOnlyAtBootTime (
>    }
>  }
> 
> +/**
> +  Return TRUE if ExitBootServices () has been called.
> +
> +  @retval TRUE If ExitBootServices () has been called. FALSE if ExitBootServices
> () has not been called.
> +**/
> +BOOLEAN
> +AtRuntime (
> +  VOID
> +  )
> +{
> +  return EfiAtRuntime ();
> +}
> +
> +/**
> +  Initialize the variable cache buffer as an empty variable store.
> +
> +  @param[out]     VariableCacheBuffer     A pointer to pointer of a cache
> variable store.
> +  @param[in,out]  TotalVariableCacheSize  On input, the minimum size needed
> for the UEFI variable store cache
> +                                          buffer that is allocated. On output, the actual size of the
> buffer allocated.
> +                                          If TotalVariableCacheSize is zero, a buffer will not be
> allocated and the
> +                                          function will return with EFI_SUCCESS.
> +
> +  @retval EFI_SUCCESS             The variable cache was allocated and initialized
> successfully.
> +  @retval EFI_INVALID_PARAMETER   A given pointer is NULL or an invalid
> variable store size was specified.
> +  @retval EFI_OUT_OF_RESOURCES    Insufficient resources are available to
> allocate the variable store cache buffer.
> +
> +**/
> +EFI_STATUS
> +InitVariableCache (
> +  OUT    VARIABLE_STORE_HEADER   **VariableCacheBuffer,
> +  IN OUT UINTN                   *TotalVariableCacheSize
> +  )
> +{
> +  VARIABLE_STORE_HEADER   *VariableCacheStorePtr;
> +
> +  if (TotalVariableCacheSize == NULL) {
> +    return EFI_INVALID_PARAMETER;
> +  }
> +  if (*TotalVariableCacheSize == 0) {
> +    return EFI_SUCCESS;
> +  }
> +  if (VariableCacheBuffer == NULL || *TotalVariableCacheSize < sizeof
> (VARIABLE_STORE_HEADER)) {
> +    return EFI_INVALID_PARAMETER;
> +  }
> +  *TotalVariableCacheSize = ALIGN_VALUE (*TotalVariableCacheSize, sizeof
> (UINT32));
> +
> +  //
> +  // Allocate NV Storage Cache and initialize it to all 1's (like an erased FV)
> +  //
> +  *VariableCacheBuffer =  (VARIABLE_STORE_HEADER *) AllocateRuntimePages
> (
> +                            EFI_SIZE_TO_PAGES (*TotalVariableCacheSize)
> +                            );
> +  if (*VariableCacheBuffer == NULL) {
> +    return EFI_OUT_OF_RESOURCES;
> +  }
> +  VariableCacheStorePtr = *VariableCacheBuffer;
> +  SetMem32 ((VOID *) VariableCacheStorePtr, *TotalVariableCacheSize,
> (UINT32) 0xFFFFFFFF);
> +
> +  ZeroMem ((VOID *) VariableCacheStorePtr, sizeof
> (VARIABLE_STORE_HEADER));
> +  VariableCacheStorePtr->Size    = (UINT32) *TotalVariableCacheSize;
> +  VariableCacheStorePtr->Format  = VARIABLE_STORE_FORMATTED;
> +  VariableCacheStorePtr->State   = VARIABLE_STORE_HEALTHY;
> +
> +  return EFI_SUCCESS;
> +}
> +
>  /**
>    Initialize the communicate buffer using DataSize and Function.
> 
> @@ -425,7 +503,169 @@ Done:
>  }
> 
>  /**
> -  This code finds variable in storage blocks (Volatile or Non-Volatile).
> +  Signals SMM to synchronize any pending variable updates with the runtime
> cache(s).
> +
> +**/
> +VOID
> +SyncRuntimeCache (
> +  VOID
> +  )
> +{
> +  //
> +  // Init the communicate buffer. The buffer data size is:
> +  // SMM_COMMUNICATE_HEADER_SIZE +
> SMM_VARIABLE_COMMUNICATE_HEADER_SIZE.
> +  //
> +  InitCommunicateBuffer (NULL, 0,
> SMM_VARIABLE_FUNCTION_SYNC_RUNTIME_CACHE);
> +
> +  //
> +  // Send data to SMM.
> +  //
> +  SendCommunicateBuffer (0);
> +}
> +
> +/**
> +  Check whether a SMI must be triggered to retrieve pending cache updates.
> +
> +  If the variable HOB was finished being flushed since the last check for a
> runtime cache update, this function
> +  will prevent the HOB cache from being used for future runtime cache hits.
> +
> +**/
> +VOID
> +CheckForRuntimeCacheSync (
> +  VOID
> +  )
> +{
> +  if (mVariableRuntimeCachePendingUpdate) {
> +    SyncRuntimeCache ();
> +  }
> +  ASSERT (!mVariableRuntimeCachePendingUpdate);
> +
> +  //
> +  // The HOB variable data may have finished being flushed in the runtime cache
> sync update
> +  //
> +  if (mHobFlushComplete && mVariableRuntimeHobCacheBuffer != NULL) {
> +    if (!EfiAtRuntime ()) {
> +      FreePages (mVariableRuntimeHobCacheBuffer, EFI_SIZE_TO_PAGES
> (mVariableRuntimeHobCacheBufferSize));
> +    }
> +    mVariableRuntimeHobCacheBuffer = NULL;
> +  }
> +}
> +
> +/**
> +  Finds the given variable in a runtime cache variable store.
> +
> +  Caution: This function may receive untrusted input.
> +  The data size is external input, so this function will validate it carefully to
> avoid buffer overflow.
> +
> +  @param[in]      VariableName       Name of Variable to be found.
> +  @param[in]      VendorGuid         Variable vendor GUID.
> +  @param[out]     Attributes         Attribute value of the variable found.
> +  @param[in, out] DataSize           Size of Data found. If size is less than the
> +                                     data, this value contains the required size.
> +  @param[out]     Data               Data pointer.
> +
> +  @retval EFI_SUCCESS                Found the specified variable.
> +  @retval EFI_INVALID_PARAMETER      Invalid parameter.
> +  @retval EFI_NOT_FOUND              The specified variable could not be found.
> +
> +**/
> +EFI_STATUS
> +FindVariableInRuntimeCache (
> +  IN      CHAR16                            *VariableName,
> +  IN      EFI_GUID                          *VendorGuid,
> +  OUT     UINT32                            *Attributes OPTIONAL,
> +  IN OUT  UINTN                             *DataSize,
> +  OUT     VOID                              *Data OPTIONAL
> +  )
> +{
> +  EFI_STATUS              Status;
> +  UINTN                   TempDataSize;
> +  VARIABLE_POINTER_TRACK  RtPtrTrack;
> +  VARIABLE_STORE_TYPE     StoreType;
> +  VARIABLE_STORE_HEADER   *VariableStoreList[VariableStoreTypeMax];
> +
> +  Status = EFI_NOT_FOUND;
> +
> +  if (VariableName == NULL || VendorGuid == NULL || DataSize == NULL) {
> +    return EFI_INVALID_PARAMETER;
> +  }
> +
> +  //
> +  // The UEFI specification restricts Runtime Services callers from invoking the
> same or certain other Runtime Service
> +  // functions prior to completion and return from a previous Runtime Service
> call. These restrictions prevent
> +  // a GetVariable () or GetNextVariable () call from being issued until a prior call
> has returned. The runtime
> +  // cache read lock should always be free when entering this function.
> +  //
> +  ASSERT (!mVariableRuntimeCacheReadLock);
> +
> +  mVariableRuntimeCacheReadLock = TRUE;
> +  CheckForRuntimeCacheSync ();
> +
> +  if (!mVariableRuntimeCachePendingUpdate) {
> +    //
> +    // 0: Volatile, 1: HOB, 2: Non-Volatile.
> +    // The index and attributes mapping must be kept in this order as
> FindVariable
> +    // makes use of this mapping to implement search algorithm.
> +    //
> +    VariableStoreList[VariableStoreTypeVolatile] =
> mVariableRuntimeVolatileCacheBuffer;
> +    VariableStoreList[VariableStoreTypeHob]      =
> mVariableRuntimeHobCacheBuffer;
> +    VariableStoreList[VariableStoreTypeNv]       =
> mVariableRuntimeNvCacheBuffer;
> +
> +    for (StoreType = (VARIABLE_STORE_TYPE) 0; StoreType <
> VariableStoreTypeMax; StoreType++) {
> +      if (VariableStoreList[StoreType] == NULL) {
> +        continue;
> +      }
> +
> +      RtPtrTrack.StartPtr = GetStartPointer (VariableStoreList[StoreType]);
> +      RtPtrTrack.EndPtr   = GetEndPointer   (VariableStoreList[StoreType]);
> +      RtPtrTrack.Volatile = (BOOLEAN) (StoreType == VariableStoreTypeVolatile);
> +
> +      Status = FindVariableEx (VariableName, VendorGuid, FALSE, &RtPtrTrack,
> mVariableAuthFormat);
> +      if (!EFI_ERROR (Status)) {
> +        break;
> +      }
> +    }
> +
> +    if (!EFI_ERROR (Status)) {
> +      //
> +      // Get data size
> +      //
> +      TempDataSize = DataSizeOfVariable (RtPtrTrack.CurrPtr,
> mVariableAuthFormat);
> +      ASSERT (TempDataSize != 0);
> +
> +      if (*DataSize >= TempDataSize) {
> +        if (Data == NULL) {
> +          Status = EFI_INVALID_PARAMETER;
> +          goto Done;
> +        }
> +
> +        CopyMem (Data, GetVariableDataPtr (RtPtrTrack.CurrPtr,
> mVariableAuthFormat), TempDataSize);
> +        if (Attributes != NULL) {
> +          *Attributes = RtPtrTrack.CurrPtr->Attributes;
> +        }
> +
> +        *DataSize = TempDataSize;
> +
> +        UpdateVariableInfo (VariableName, VendorGuid, RtPtrTrack.Volatile,
> TRUE, FALSE, FALSE, TRUE, &mVariableInfo);
> +
> +        Status = EFI_SUCCESS;
> +        goto Done;
> +      } else {
> +        *DataSize = TempDataSize;
> +        Status = EFI_BUFFER_TOO_SMALL;
> +        goto Done;
> +      }
> +    }
> +  }
> +
> +Done:
> +  mVariableRuntimeCacheReadLock = FALSE;
> +
> +  return Status;
> +}
> +
> +/**
> +  Finds the given variable in a variable store in SMM.
> 
>    Caution: This function may receive untrusted input.
>    The data size is external input, so this function will validate it carefully to avoid
> buffer overflow.
> @@ -437,20 +677,18 @@ Done:
>                                       data, this value contains the required size.
>    @param[out]     Data               Data pointer.
> 
> +  @retval EFI_SUCCESS                Found the specified variable.
>    @retval EFI_INVALID_PARAMETER      Invalid parameter.
> -  @retval EFI_SUCCESS                Find the specified variable.
> -  @retval EFI_NOT_FOUND              Not found.
> -  @retval EFI_BUFFER_TO_SMALL        DataSize is too small for the result.
> +  @retval EFI_NOT_FOUND              The specified variable could not be found.
> 
>  **/
>  EFI_STATUS
> -EFIAPI
> -RuntimeServiceGetVariable (
> +FindVariableInSmm (
>    IN      CHAR16                            *VariableName,
>    IN      EFI_GUID                          *VendorGuid,
>    OUT     UINT32                            *Attributes OPTIONAL,
>    IN OUT  UINTN                             *DataSize,
> -  OUT     VOID                              *Data
> +  OUT     VOID                              *Data OPTIONAL
>    )
>  {
>    EFI_STATUS                                Status;
> @@ -474,8 +712,6 @@ RuntimeServiceGetVariable (
>      return EFI_INVALID_PARAMETER;
>    }
> 
> -  AcquireLockOnlyAtBootTime(&mVariableServicesLock);
> -
>    //
>    // Init the communicate buffer. The buffer data size is:
>    // SMM_COMMUNICATE_HEADER_SIZE +
> SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + PayloadSize.
> @@ -488,7 +724,7 @@ RuntimeServiceGetVariable (
>    }
>    PayloadSize = OFFSET_OF
> (SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name) +
> VariableNameSize + TempDataSize;
> 
> -  Status = InitCommunicateBuffer ((VOID **)&SmmVariableHeader, PayloadSize,
> SMM_VARIABLE_FUNCTION_GET_VARIABLE);
> +  Status = InitCommunicateBuffer ((VOID **) &SmmVariableHeader,
> PayloadSize, SMM_VARIABLE_FUNCTION_GET_VARIABLE);
>    if (EFI_ERROR (Status)) {
>      goto Done;
>    }
> @@ -534,11 +770,58 @@ RuntimeServiceGetVariable (
>    }
> 
>  Done:
> +  return Status;
> +}
> +
> +/**
> +  This code finds variable in storage blocks (Volatile or Non-Volatile).
> +
> +  Caution: This function may receive untrusted input.
> +  The data size is external input, so this function will validate it carefully to
> avoid buffer overflow.
> +
> +  @param[in]      VariableName       Name of Variable to be found.
> +  @param[in]      VendorGuid         Variable vendor GUID.
> +  @param[out]     Attributes         Attribute value of the variable found.
> +  @param[in, out] DataSize           Size of Data found. If size is less than the
> +                                     data, this value contains the required size.
> +  @param[out]     Data               Data pointer.
> +
> +  @retval EFI_INVALID_PARAMETER      Invalid parameter.
> +  @retval EFI_SUCCESS                Find the specified variable.
> +  @retval EFI_NOT_FOUND              Not found.
> +  @retval EFI_BUFFER_TO_SMALL        DataSize is too small for the result.
> +
> +**/
> +EFI_STATUS
> +EFIAPI
> +RuntimeServiceGetVariable (
> +  IN      CHAR16                            *VariableName,
> +  IN      EFI_GUID                          *VendorGuid,
> +  OUT     UINT32                            *Attributes OPTIONAL,
> +  IN OUT  UINTN                             *DataSize,
> +  OUT     VOID                              *Data
> +  )
> +{
> +  EFI_STATUS                                Status;
> +
> +  if (VariableName == NULL || VendorGuid == NULL || DataSize == NULL) {
> +    return EFI_INVALID_PARAMETER;
> +  }
> +  if (VariableName[0] == 0) {
> +    return EFI_NOT_FOUND;
> +  }
> +
> +  AcquireLockOnlyAtBootTime (&mVariableServicesLock);
> +  if (FeaturePcdGet (PcdEnableVariableRuntimeCache)) {
> +    Status = FindVariableInRuntimeCache (VariableName, VendorGuid, Attributes,
> DataSize, Data);
> +  } else {
> +    Status = FindVariableInSmm (VariableName, VendorGuid, Attributes, DataSize,
> Data);
> +  }
>    ReleaseLockOnlyAtBootTime (&mVariableServicesLock);
> +
>    return Status;
>  }
> 
> -
>  /**
>    This code Finds the Next available variable.
> 
> @@ -870,6 +1153,17 @@ OnReadyToBoot (
>    //
>    SendCommunicateBuffer (0);
> 
> +  //
> +  // Install the system configuration table for variable info data captured
> +  //
> +  if (FeaturePcdGet (PcdEnableVariableRuntimeCache) && FeaturePcdGet
> (PcdVariableCollectStatistics)) {
> +    if (mVariableAuthFormat) {
> +      gBS->InstallConfigurationTable (&gEfiAuthenticatedVariableGuid,
> mVariableInfo);
> +    } else {
> +      gBS->InstallConfigurationTable (&gEfiVariableGuid, mVariableInfo);
> +    }
> +  }
> +
>    gBS->CloseEvent (Event);
>  }
> 
> @@ -893,6 +1187,9 @@ VariableAddressChangeEvent (
>  {
>    EfiConvertPointer (0x0, (VOID **) &mVariableBuffer);
>    EfiConvertPointer (0x0, (VOID **) &mSmmCommunication);
> +  EfiConvertPointer (EFI_OPTIONAL_PTR, (VOID **)
> &mVariableRuntimeHobCacheBuffer);
> +  EfiConvertPointer (EFI_OPTIONAL_PTR, (VOID **)
> &mVariableRuntimeNvCacheBuffer);
> +  EfiConvertPointer (EFI_OPTIONAL_PTR, (VOID **)
> &mVariableRuntimeVolatileCacheBuffer);
>  }
> 
>  /**
> @@ -969,6 +1266,159 @@ Done:
>    return Status;
>  }
> 
> +/**
> +  This code gets information needed from SMM for runtime cache initialization.
> +
> +  @param[out] TotalHobStorageSize         Output pointer for the total HOB
> storage size in bytes.
> +  @param[out] TotalNvStorageSize          Output pointer for the total non-
> volatile storage size in bytes.
> +  @param[out] TotalVolatileStorageSize    Output pointer for the total volatile
> storage size in bytes.
> +  @param[out] AuthenticatedVariableUsage  Output pointer that indicates if
> authenticated variables are to be used.
> +
> +  @retval EFI_SUCCESS                     Retrieved the size successfully.
> +  @retval EFI_INVALID_PARAMETER           TotalNvStorageSize parameter is
> NULL.
> +  @retval EFI_OUT_OF_RESOURCES            The memory resources needed for a
> CommBuffer are not available.
> +  @retval Others                          Could not retrieve the size successfully.
> +
> +**/
> +EFI_STATUS
> +GetRuntimeCacheInfo (
> +  OUT UINTN                         *TotalHobStorageSize,
> +  OUT UINTN                         *TotalNvStorageSize,
> +  OUT UINTN                         *TotalVolatileStorageSize,
> +  OUT BOOLEAN                       *AuthenticatedVariableUsage
> +  )
> +{
> +  EFI_STATUS                                          Status;
> +  SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO
> *SmmGetRuntimeCacheInfo;
> +  EFI_SMM_COMMUNICATE_HEADER                          *SmmCommunicateHeader;
> +  SMM_VARIABLE_COMMUNICATE_HEADER
> *SmmVariableFunctionHeader;
> +  UINTN                                               CommSize;
> +  UINT8                                               *CommBuffer;
> +
> +  SmmGetRuntimeCacheInfo = NULL;
> +  CommBuffer = mVariableBuffer;
> +
> +  if (TotalHobStorageSize == NULL || TotalNvStorageSize == NULL ||
> TotalVolatileStorageSize == NULL || AuthenticatedVariableUsage == NULL) {
> +    return EFI_INVALID_PARAMETER;
> +  }
> +
> +  if (CommBuffer == NULL) {
> +    return EFI_OUT_OF_RESOURCES;
> +  }
> +
> +  AcquireLockOnlyAtBootTime (&mVariableServicesLock);
> +
> +  CommSize = SMM_COMMUNICATE_HEADER_SIZE +
> SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + sizeof
> (SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO);
> +  ZeroMem (CommBuffer, CommSize);
> +
> +  SmmCommunicateHeader = (EFI_SMM_COMMUNICATE_HEADER *)
> CommBuffer;
> +  CopyGuid (&SmmCommunicateHeader->HeaderGuid,
> &gEfiSmmVariableProtocolGuid);
> +  SmmCommunicateHeader->MessageLength =
> SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + sizeof
> (SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO);
> +
> +  SmmVariableFunctionHeader = (SMM_VARIABLE_COMMUNICATE_HEADER *)
> SmmCommunicateHeader->Data;
> +  SmmVariableFunctionHeader->Function =
> SMM_VARIABLE_FUNCTION_GET_RUNTIME_CACHE_INFO;
> +  SmmGetRuntimeCacheInfo =
> (SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO *)
> SmmVariableFunctionHeader->Data;
> +
> +  //
> +  // Send data to SMM.
> +  //
> +  Status = mSmmCommunication->Communicate (mSmmCommunication,
> CommBuffer, &CommSize);
> +  ASSERT_EFI_ERROR (Status);
> +  if (CommSize <= SMM_VARIABLE_COMMUNICATE_HEADER_SIZE) {
> +    Status = EFI_BAD_BUFFER_SIZE;
> +    goto Done;
> +  }
> +
> +  Status = SmmVariableFunctionHeader->ReturnStatus;
> +  if (EFI_ERROR (Status)) {
> +    goto Done;
> +  }
> +
> +  //
> +  // Get data from SMM.
> +  //
> +  *TotalHobStorageSize = SmmGetRuntimeCacheInfo->TotalHobStorageSize;
> +  *TotalNvStorageSize = SmmGetRuntimeCacheInfo->TotalNvStorageSize;
> +  *TotalVolatileStorageSize = SmmGetRuntimeCacheInfo-
> >TotalVolatileStorageSize;
> +  *AuthenticatedVariableUsage = SmmGetRuntimeCacheInfo-
> >AuthenticatedVariableUsage;
> +
> +Done:
> +  ReleaseLockOnlyAtBootTime (&mVariableServicesLock);
> +  return Status;
> +}
> +
> +/**
> +  Sends the runtime variable cache context information to SMM.
> +
> +  @retval EFI_SUCCESS               Retrieved the size successfully.
> +  @retval EFI_INVALID_PARAMETER     TotalNvStorageSize parameter is NULL.
> +  @retval EFI_OUT_OF_RESOURCES      The memory resources needed for a
> CommBuffer are not available.
> +  @retval Others                    Could not retrieve the size successfully.;
> +
> +**/
> +EFI_STATUS
> +SendRuntimeVariableCacheContextToSmm (
> +  VOID
> +  )
> +{
> +  EFI_STATUS                                                Status;
> +  SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT
> *SmmRuntimeVarCacheContext;
> +  EFI_SMM_COMMUNICATE_HEADER
> *SmmCommunicateHeader;
> +  SMM_VARIABLE_COMMUNICATE_HEADER
> *SmmVariableFunctionHeader;
> +  UINTN                                                     CommSize;
> +  UINT8                                                     *CommBuffer;
> +
> +  SmmRuntimeVarCacheContext = NULL;
> +  CommBuffer = mVariableBuffer;
> +
> +  if (CommBuffer == NULL) {
> +    return EFI_OUT_OF_RESOURCES;
> +  }
> +
> +  AcquireLockOnlyAtBootTime (&mVariableServicesLock);
> +
> +  //
> +  // Init the communicate buffer. The buffer data size is:
> +  // SMM_COMMUNICATE_HEADER_SIZE +
> SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + sizeof
> (SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT);
> +  //
> +  CommSize = SMM_COMMUNICATE_HEADER_SIZE +
> SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + sizeof
> (SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT);
> +  ZeroMem (CommBuffer, CommSize);
> +
> +  SmmCommunicateHeader = (EFI_SMM_COMMUNICATE_HEADER *)
> CommBuffer;
> +  CopyGuid (&SmmCommunicateHeader->HeaderGuid,
> &gEfiSmmVariableProtocolGuid);
> +  SmmCommunicateHeader->MessageLength =
> SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + sizeof
> (SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT);
> +
> +  SmmVariableFunctionHeader = (SMM_VARIABLE_COMMUNICATE_HEADER *)
> SmmCommunicateHeader->Data;
> +  SmmVariableFunctionHeader->Function =
> SMM_VARIABLE_FUNCTION_INIT_RUNTIME_VARIABLE_CACHE_CONTEXT;
> +  SmmRuntimeVarCacheContext =
> (SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT *)
> SmmVariableFunctionHeader->Data;
> +
> +  SmmRuntimeVarCacheContext->RuntimeHobCache =
> mVariableRuntimeHobCacheBuffer;
> +  SmmRuntimeVarCacheContext->RuntimeVolatileCache =
> mVariableRuntimeVolatileCacheBuffer;
> +  SmmRuntimeVarCacheContext->RuntimeNvCache =
> mVariableRuntimeNvCacheBuffer;
> +  SmmRuntimeVarCacheContext->PendingUpdate =
> &mVariableRuntimeCachePendingUpdate;
> +  SmmRuntimeVarCacheContext->ReadLock =
> &mVariableRuntimeCacheReadLock;
> +  SmmRuntimeVarCacheContext->HobFlushComplete = &mHobFlushComplete;
> +
> +  //
> +  // Send data to SMM.
> +  //
> +  Status = mSmmCommunication->Communicate (mSmmCommunication,
> CommBuffer, &CommSize);
> +  ASSERT_EFI_ERROR (Status);
> +  if (CommSize <= SMM_VARIABLE_COMMUNICATE_HEADER_SIZE) {
> +    Status = EFI_BAD_BUFFER_SIZE;
> +    goto Done;
> +  }
> +
> +  Status = SmmVariableFunctionHeader->ReturnStatus;
> +  if (EFI_ERROR (Status)) {
> +    goto Done;
> +  }
> +
> +Done:
> +  ReleaseLockOnlyAtBootTime (&mVariableServicesLock);
> +  return Status;
> +}
> +
>  /**
>    Initialize variable service and install Variable Architectural protocol.
> 
> @@ -985,7 +1435,7 @@ SmmVariableReady (
>  {
>    EFI_STATUS                                Status;
> 
> -  Status = gBS->LocateProtocol (&gEfiSmmVariableProtocolGuid, NULL, (VOID
> **)&mSmmVariable);
> +  Status = gBS->LocateProtocol (&gEfiSmmVariableProtocolGuid, NULL, (VOID
> **) &mSmmVariable);
>    if (EFI_ERROR (Status)) {
>      return;
>    }
> @@ -1007,6 +1457,42 @@ SmmVariableReady (
>    //
>    mVariableBufferPhysical = mVariableBuffer;
> 
> +  if (FeaturePcdGet (PcdEnableVariableRuntimeCache)) {
> +    DEBUG ((DEBUG_INFO, "Variable driver runtime cache is enabled.\n"));
> +    //
> +    // Allocate runtime variable cache memory buffers.
> +    //
> +    Status =  GetRuntimeCacheInfo (
> +                &mVariableRuntimeHobCacheBufferSize,
> +                &mVariableRuntimeNvCacheBufferSize,
> +                &mVariableRuntimeVolatileCacheBufferSize,
> +                &mVariableAuthFormat
> +                );
> +    if (!EFI_ERROR (Status)) {
> +      Status = InitVariableCache (&mVariableRuntimeHobCacheBuffer,
> &mVariableRuntimeHobCacheBufferSize);
> +      if (!EFI_ERROR (Status)) {
> +        Status = InitVariableCache (&mVariableRuntimeNvCacheBuffer,
> &mVariableRuntimeNvCacheBufferSize);
> +        if (!EFI_ERROR (Status)) {
> +          Status = InitVariableCache (&mVariableRuntimeVolatileCacheBuffer,
> &mVariableRuntimeVolatileCacheBufferSize);
> +          if (!EFI_ERROR (Status)) {
> +            Status = SendRuntimeVariableCacheContextToSmm ();
> +            if (!EFI_ERROR (Status)) {
> +              SyncRuntimeCache ();
> +            }
> +          }
> +        }
> +      }
> +      if (EFI_ERROR (Status)) {
> +        mVariableRuntimeHobCacheBuffer = NULL;
> +        mVariableRuntimeNvCacheBuffer = NULL;
> +        mVariableRuntimeVolatileCacheBuffer = NULL;
> +      }
> +    }
> +    ASSERT_EFI_ERROR (Status);
> +  } else {
> +    DEBUG ((DEBUG_INFO, "Variable driver runtime cache is disabled.\n"));
> +  }
> +
>    gRT->GetVariable         = RuntimeServiceGetVariable;
>    gRT->GetNextVariableName = RuntimeServiceGetNextVariableName;
>    gRT->SetVariable         = RuntimeServiceSetVariable;
> --
> 2.16.2.windows.1


^ permalink raw reply	[flat|nested] 14+ messages in thread

end of thread, other threads:[~2019-11-02  1:36 UTC | newest]

Thread overview: 14+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2019-11-01 17:34 [PATCH V7 00/10] UEFI Variable SMI Reduction Kubacki, Michael A
2019-11-01 17:34 ` [PATCH V7 01/10] MdeModulePkg/Variable: Consolidate common parsing functions Kubacki, Michael A
2019-11-01 17:34 ` [PATCH V7 02/10] MdeModulePkg/Variable: Parameterize GetNextVariableInternal () stores Kubacki, Michael A
2019-11-01 17:34 ` [PATCH V7 03/10] MdeModulePkg/Variable: Parameterize VARIABLE_INFO_ENTRY buffer Kubacki, Michael A
2019-11-01 17:34 ` [PATCH V7 04/10] MdeModulePkg/Variable: Parameterize auth status in VariableParsing Kubacki, Michael A
2019-11-01 17:34 ` [PATCH V7 05/10] MdeModulePkg/Variable: Add a file for NV variable functions Kubacki, Michael A
2019-11-01 17:34 ` [PATCH V7 06/10] MdeModulePkg VariableInfo: Always consider RT DXE and SMM stats Kubacki, Michael A
2019-11-01 17:34 ` [PATCH V7 07/10] MdeModulePkg/Variable: Add RT GetVariable() cache support Kubacki, Michael A
2019-11-02  1:36   ` Wang, Jian J
2019-11-01 17:34 ` [PATCH V7 08/10] MdeModulePkg/Variable: Add RT GetNextVariableName() " Kubacki, Michael A
2019-11-01 17:34 ` [PATCH V7 09/10] OvmfPkg: Disable variable runtime cache Kubacki, Michael A
2019-11-01 17:34 ` [PATCH V7 10/10] MdeModulePkg: Enable variable runtime cache by default Kubacki, Michael A
2019-11-01 22:19 ` [PATCH V7 00/10] UEFI Variable SMI Reduction Laszlo Ersek
2019-11-01 23:17   ` Kubacki, Michael A

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox