public inbox for devel@edk2.groups.io
 help / color / mirror / Atom feed
* [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation
@ 2018-03-02  0:03 Laszlo Ersek
  2018-03-02  0:03 ` [PATCH 01/20] OvmfPkg/MemEncryptSevLib: rewrap to 79 characters width Laszlo Ersek
                   ` (21 more replies)
  0 siblings, 22 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:03 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

Repo:   https://github.com/lersek/edk2.git
Branch: sev_smram_save_state_map

This patch series replaces the following patch from Brijesh:

  [PATCH v2 1/2] OvmfPkg/AmdSevDxe: Clear the C-bit from SMM Saved State
  http://mid.mail-archive.com/20180228161415.28723-2-brijesh.singh@amd.com
  https://lists.01.org/pipermail/edk2-devel/2018-February/022016.html

The series modifies four modules under OvmfPkg:
- MemEncryptSevLib
- PlatformPei
- SmmCpuFeaturesLib
- AmdSevDxe

Patches 01 through 16 are cleanups for these modules, without change in
functionality. The series is formatted with 20 lines of context, for
simplifying the review of these patches.

Patches 17 through 20 (one patch per module listed above) implement
$SUBJECT:

- MemEncryptSevLib gets a new helper function used by the other three
  modules.

- PlatformPei makes sure that DXE stays out of the page(s) where the
  initial SMRAM save state map lives.

- SmmCpuFeaturesLib and AmdSevDxe basically do what they did in
  Brijesh's patch, just better separated, and with minor tweaks.

The series is bisectable.

I regression-tested my usual non-SEV guests (with Brijesh's v2 2/2 patch
applied on top, from the above-referenced series), which covers i440fx
(no SMM, X64), q35 (SMM, IA32 and IA32X64), Fedora and Windows, normal
boot and S3.

I also tried to test the series with SEV guests (again with Brijesh's v2
2/2 patch applied on top). Unfortunately, I didn't get good results with
or without SMM. Without SMM, the guest OS boots to a point, but then it
gets stuck with the CPU spinning. With SMM, OVMF gets stuck in SMBASE
relocation.

I should mention however that my SEV host setup dates back to November
2017, including host kernel, QEMU and guest OS. I suppose all those
components have seen many changes since, on the respective upstream
lists. I'll have to work with Brijesh to update my SEV host to the
latest bits.

Until then, Brijesh, can you please test this series? Thank you!

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>

Cheers
Laszlo

Laszlo Ersek (20):
  OvmfPkg/MemEncryptSevLib: rewrap to 79 characters width
  OvmfPkg/MemEncryptSevLib: clean up MemEncryptSevIsEnabled() decl
  OvmfPkg/MemEncryptSevLib: clean up MemEncryptSevClearPageEncMask()
    decl
  OvmfPkg/MemEncryptSevLib: clean up MemEncryptSevSetPageEncMask() decl
  OvmfPkg/MemEncryptSevLib: clean up SetMemoryEncDec() comment block
  OvmfPkg/MemEncryptSevLib: clean up
    InternalMemEncryptSevSetMemoryDecrypted() decl
  OvmfPkg/MemEncryptSevLib: clean up
    InternalMemEncryptSevSetMemoryEncrypted() decl
  OvmfPkg/MemEncryptSevLib: sort #includes, and entries in INF file
    sections
  OvmfPkg/PlatformPei: sort #includes in "AmdSev.c"
  OvmfPkg/SmmCpuFeaturesLib: rewrap to 79 columns
  OvmfPkg/SmmCpuFeaturesLib: upper-case the "static" keyword
  OvmfPkg/SmmCpuFeaturesLib: sort #includes, and entries in INF file
    sections
  OvmfPkg/SmmCpuFeaturesLib: remove unneeded #includes and
    LibraryClasses
  OvmfPkg/AmdSevDxe: rewrap to 79 characters width
  OvmfPkg/AmdSevDxe: sort #includes, and entries in INF file sections
  OvmfPkg/AmdSevDxe: refresh #includes and LibraryClasses
  OvmfPkg/MemEncryptSevLib: find pages of initial SMRAM save state map
  OvmfPkg/PlatformPei: SEV: allocate pages of initial SMRAM save state
    map
  OvmfPkg/SmmCpuFeaturesLib: SEV: encrypt+free pages of init. save state
    map
  OvmfPkg/AmdSevDxe: decrypt the pages of the initial SMRAM save state
    map

 OvmfPkg/AmdSevDxe/AmdSevDxe.c                                   |  88 ++-
 OvmfPkg/AmdSevDxe/AmdSevDxe.inf                                 |  25 +-
 OvmfPkg/Include/Library/MemEncryptSevLib.h                      |  89 ++-
 OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf   |  17 +-
 OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c    |  72 ++-
 OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c |  66 +-
 OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c     |  74 ++-
 OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c        | 172 ++++--
 OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h        | 137 +++--
 OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c           | 650 ++++++++++++++++----
 OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf         |  13 +-
 OvmfPkg/PlatformPei/AmdSev.c                                    |  36 +-
 12 files changed, 1067 insertions(+), 372 deletions(-)

-- 
2.14.1.3.gb7cf6e02401b



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

* [PATCH 01/20] OvmfPkg/MemEncryptSevLib: rewrap to 79 characters width
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
@ 2018-03-02  0:03 ` Laszlo Ersek
  2018-03-02  0:33   ` Kinney, Michael D
  2018-03-02  0:03 ` [PATCH 02/20] OvmfPkg/MemEncryptSevLib: clean up MemEncryptSevIsEnabled() decl Laszlo Ersek
                   ` (20 subsequent siblings)
  21 siblings, 1 reply; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:03 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

There are many overlong lines; it's hard to work with the library like
this. Rewrap all files to 79 columns.

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf   |   7 +-
 OvmfPkg/Include/Library/MemEncryptSevLib.h                      |  20 ++-
 OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h        | 111 ++++++++------
 OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c    |  34 +++--
 OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c |   8 +-
 OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c     |  58 ++++---
 OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c        | 158 +++++++++++++-------
 7 files changed, 253 insertions(+), 143 deletions(-)

diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf b/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
index 3cfd80a28c1d..81b075194ace 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
@@ -1,45 +1,48 @@
 ## @file
 #  Library provides the helper functions for SEV guest
 #
 # Copyright (c) 2017 Advanced Micro Devices. All rights reserved.<BR>
 #
 #  This program and the accompanying materials
 #  are licensed and made available under the terms and conditions of the BSD
 #  License which accompanies this distribution. The full text of the license
 #  may be found at http://opensource.org/licenses/bsd-license.php
+#
 #  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-#  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR
+#  IMPLIED.
 #
 #
 ##
 
 [Defines]
   INF_VERSION                    = 1.25
   BASE_NAME                      = MemEncryptSevLib
   FILE_GUID                      = c1594631-3888-4be4-949f-9c630dbc842b
   MODULE_TYPE                    = BASE
   VERSION_STRING                 = 1.0
   LIBRARY_CLASS                  = MemEncryptSevLib|PEIM DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER UEFI_DRIVER
 
 #
-# The following information is for reference only and not required by the build tools.
+# The following information is for reference only and not required by the build
+# tools.
 #
 # VALID_ARCHITECTURES           = IA32 X64
 #
 
 [Packages]
   MdePkg/MdePkg.dec
   MdeModulePkg/MdeModulePkg.dec
   OvmfPkg/OvmfPkg.dec
   UefiCpuPkg/UefiCpuPkg.dec
 
 [Sources.X64]
   MemEncryptSevLibInternal.c
   X64/MemEncryptSevLib.c
   X64/VirtualMemory.c
 
 [Sources.IA32]
   MemEncryptSevLibInternal.c
   Ia32/MemEncryptSevLib.c
 
 [LibraryClasses]
diff --git a/OvmfPkg/Include/Library/MemEncryptSevLib.h b/OvmfPkg/Include/Library/MemEncryptSevLib.h
index b6753762423e..4f3ba9f22cb4 100644
--- a/OvmfPkg/Include/Library/MemEncryptSevLib.h
+++ b/OvmfPkg/Include/Library/MemEncryptSevLib.h
@@ -18,64 +18,68 @@
 #define _MEM_ENCRYPT_SEV_LIB_H_
 
 #include <Base.h>
 
 /**
   Returns a boolean to indicate whether SEV is enabled
 
   @retval TRUE           SEV is active
   @retval FALSE          SEV is not enabled
   **/
 BOOLEAN
 EFIAPI
 MemEncryptSevIsEnabled (
   VOID
   );
 
 /**
   This function clears memory encryption bit for the memory region specified
   by BaseAddress and Number of pages from the current page table context.
 
-  @param[in]  BaseAddress           The physical address that is the start address
-                                    of a memory region.
-  @param[in]  NumberOfPages         The number of pages from start memory region.
+  @param[in]  BaseAddress           The physical address that is the start
+                                    address of a memory region.
+  @param[in]  NumberOfPages         The number of pages from start memory
+                                    region.
   @param[in]  Flush                 Flush the caches before clearing the bit
                                     (mostly TRUE except MMIO addresses)
 
-  @retval RETURN_SUCCESS            The attributes were cleared for the memory region.
+  @retval RETURN_SUCCESS            The attributes were cleared for the memory
+                                    region.
   @retval RETURN_INVALID_PARAMETER  Number of pages is zero.
   @retval RETURN_UNSUPPORTED        Clearing memory encryption attribute is not
                                     supported
   **/
 RETURN_STATUS
 EFIAPI
 MemEncryptSevClearPageEncMask (
   IN PHYSICAL_ADDRESS         Cr3BaseAddress,
   IN PHYSICAL_ADDRESS         BaseAddress,
   IN UINTN                    NumberOfPages,
   IN BOOLEAN                  CacheFlush
   );
 
 /**
   This function sets memory encryption bit for the memory region specified by
   BaseAddress and Number of pages from the current page table context.
 
-  @param[in]  BaseAddress           The physical address that is the start address
-                                    of a memory region.
-  @param[in]  NumberOfPages         The number of pages from start memory region.
+  @param[in]  BaseAddress           The physical address that is the start
+                                    address of a memory region.
+  @param[in]  NumberOfPages         The number of pages from start memory
+                                    region.
   @param[in]  Flush                 Flush the caches before clearing the bit
                                     (mostly TRUE except MMIO addresses)
 
-  @retval RETURN_SUCCESS            The attributes were set for the memory region.
+  @retval RETURN_SUCCESS            The attributes were set for the memory
+                                    region.
   @retval RETURN_INVALID_PARAMETER  Number of pages is zero.
   @retval RETURN_UNSUPPORTED        Clearing memory encryption attribute is not
                                     supported
   **/
 RETURN_STATUS
 EFIAPI
 MemEncryptSevSetPageEncMask (
   IN PHYSICAL_ADDRESS         Cr3BaseAddress,
   IN PHYSICAL_ADDRESS         BaseAddress,
   IN UINTN                    NumberOfPages,
   IN BOOLEAN                  CacheFlush
   );
 #endif // _MEM_ENCRYPT_SEV_LIB_H_
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h
index e7b5634b45c1..7dd1bbe0eb26 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h
@@ -1,212 +1,239 @@
 /** @file
 
   Virtual Memory Management Services to set or clear the memory encryption bit
 
-Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>
-Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
+  Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>
+  Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
 
-This program and the accompanying materials
-are licensed and made available under the terms and conditions of the BSD License
-which accompanies this distribution.  The full text of the license may be found at
-http://opensource.org/licenses/bsd-license.php
+  This program and the accompanying materials are licensed and made available
+  under the terms and conditions of the BSD License which accompanies this
+  distribution.  The full text of the license may be found at
+  http://opensource.org/licenses/bsd-license.php
 
-THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT
+  WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
-Code is derived from MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.h
+  Code is derived from MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.h
 
 **/
 
 #ifndef __VIRTUAL_MEMORY__
 #define __VIRTUAL_MEMORY__
 
 #include <Uefi.h>
 #include <Library/BaseLib.h>
 #include <Library/BaseMemoryLib.h>
 #include <Library/DebugLib.h>
 #include <Library/MemoryAllocationLib.h>
 
 #include <Library/CacheMaintenanceLib.h>
 #define SYS_CODE64_SEL 0x38
 
 #pragma pack(1)
 
 //
 // Page-Map Level-4 Offset (PML4) and
 // Page-Directory-Pointer Offset (PDPE) entries 4K & 2MB
 //
 
 typedef union {
   struct {
-    UINT64  Present:1;                // 0 = Not present in memory, 1 = Present in memory
+    UINT64  Present:1;                // 0 = Not present in memory,
+                                      //   1 = Present in memory
     UINT64  ReadWrite:1;              // 0 = Read-Only, 1= Read/Write
     UINT64  UserSupervisor:1;         // 0 = Supervisor, 1=User
-    UINT64  WriteThrough:1;           // 0 = Write-Back caching, 1=Write-Through caching
+    UINT64  WriteThrough:1;           // 0 = Write-Back caching,
+                                      //   1 = Write-Through caching
     UINT64  CacheDisabled:1;          // 0 = Cached, 1=Non-Cached
-    UINT64  Accessed:1;               // 0 = Not accessed, 1 = Accessed (set by CPU)
+    UINT64  Accessed:1;               // 0 = Not accessed,
+                                      //   1 = Accessed (set by CPU)
     UINT64  Reserved:1;               // Reserved
     UINT64  MustBeZero:2;             // Must Be Zero
     UINT64  Available:3;              // Available for use by system software
     UINT64  PageTableBaseAddress:40;  // Page Table Base Address
     UINT64  AvabilableHigh:11;        // Available for use by system software
     UINT64  Nx:1;                     // No Execute bit
   } Bits;
   UINT64    Uint64;
 } PAGE_MAP_AND_DIRECTORY_POINTER;
 
 //
 // Page Table Entry 4KB
 //
 typedef union {
   struct {
-    UINT64  Present:1;                // 0 = Not present in memory, 1 = Present in memory
+    UINT64  Present:1;                // 0 = Not present in memory,
+                                      //   1 = Present in memory
     UINT64  ReadWrite:1;              // 0 = Read-Only, 1= Read/Write
     UINT64  UserSupervisor:1;         // 0 = Supervisor, 1=User
-    UINT64  WriteThrough:1;           // 0 = Write-Back caching, 1=Write-Through caching
+    UINT64  WriteThrough:1;           // 0 = Write-Back caching,
+                                      //   1 = Write-Through caching
     UINT64  CacheDisabled:1;          // 0 = Cached, 1=Non-Cached
-    UINT64  Accessed:1;               // 0 = Not accessed, 1 = Accessed (set by CPU)
-    UINT64  Dirty:1;                  // 0 = Not Dirty, 1 = written by processor on access to page
+    UINT64  Accessed:1;               // 0 = Not accessed,
+                                      //   1 = Accessed (set by CPU)
+    UINT64  Dirty:1;                  // 0 = Not Dirty, 1 = written by
+                                      //   processor on access to page
     UINT64  PAT:1;                    //
-    UINT64  Global:1;                 // 0 = Not global page, 1 = global page TLB not cleared on CR3 write
+    UINT64  Global:1;                 // 0 = Not global page, 1 = global page
+                                      //   TLB not cleared on CR3 write
     UINT64  Available:3;              // Available for use by system software
     UINT64  PageTableBaseAddress:40;  // Page Table Base Address
     UINT64  AvabilableHigh:11;        // Available for use by system software
-    UINT64  Nx:1;                     // 0 = Execute Code, 1 = No Code Execution
+    UINT64  Nx:1;                     // 0 = Execute Code,
+                                      //   1 = No Code Execution
   } Bits;
   UINT64    Uint64;
 } PAGE_TABLE_4K_ENTRY;
 
 //
 // Page Table Entry 2MB
 //
 typedef union {
   struct {
-    UINT64  Present:1;                // 0 = Not present in memory, 1 = Present in memory
+    UINT64  Present:1;                // 0 = Not present in memory,
+                                      //   1 = Present in memory
     UINT64  ReadWrite:1;              // 0 = Read-Only, 1= Read/Write
     UINT64  UserSupervisor:1;         // 0 = Supervisor, 1=User
-    UINT64  WriteThrough:1;           // 0 = Write-Back caching, 1=Write-Through caching
+    UINT64  WriteThrough:1;           // 0 = Write-Back caching,
+                                      //   1=Write-Through caching
     UINT64  CacheDisabled:1;          // 0 = Cached, 1=Non-Cached
-    UINT64  Accessed:1;               // 0 = Not accessed, 1 = Accessed (set by CPU)
-    UINT64  Dirty:1;                  // 0 = Not Dirty, 1 = written by processor on access to page
+    UINT64  Accessed:1;               // 0 = Not accessed,
+                                      //   1 = Accessed (set by CPU)
+    UINT64  Dirty:1;                  // 0 = Not Dirty, 1 = written by
+                                      //   processor on access to page
     UINT64  MustBe1:1;                // Must be 1
-    UINT64  Global:1;                 // 0 = Not global page, 1 = global page TLB not cleared on CR3 write
+    UINT64  Global:1;                 // 0 = Not global page, 1 = global page
+                                      //   TLB not cleared on CR3 write
     UINT64  Available:3;              // Available for use by system software
     UINT64  PAT:1;                    //
     UINT64  MustBeZero:8;             // Must be zero;
     UINT64  PageTableBaseAddress:31;  // Page Table Base Address
     UINT64  AvabilableHigh:11;        // Available for use by system software
-    UINT64  Nx:1;                     // 0 = Execute Code, 1 = No Code Execution
+    UINT64  Nx:1;                     // 0 = Execute Code,
+                                      //   1 = No Code Execution
   } Bits;
   UINT64    Uint64;
 } PAGE_TABLE_ENTRY;
 
 //
 // Page Table Entry 1GB
 //
 typedef union {
   struct {
-    UINT64  Present:1;                // 0 = Not present in memory, 1 = Present in memory
+    UINT64  Present:1;                // 0 = Not present in memory,
+                                      //   1 = Present in memory
     UINT64  ReadWrite:1;              // 0 = Read-Only, 1= Read/Write
     UINT64  UserSupervisor:1;         // 0 = Supervisor, 1=User
-    UINT64  WriteThrough:1;           // 0 = Write-Back caching, 1=Write-Through caching
+    UINT64  WriteThrough:1;           // 0 = Write-Back caching,
+                                      //   1 = Write-Through caching
     UINT64  CacheDisabled:1;          // 0 = Cached, 1=Non-Cached
-    UINT64  Accessed:1;               // 0 = Not accessed, 1 = Accessed (set by CPU)
-    UINT64  Dirty:1;                  // 0 = Not Dirty, 1 = written by processor on access to page
+    UINT64  Accessed:1;               // 0 = Not accessed,
+                                      //   1 = Accessed (set by CPU)
+    UINT64  Dirty:1;                  // 0 = Not Dirty, 1 = written by
+                                      //   processor on access to page
     UINT64  MustBe1:1;                // Must be 1
-    UINT64  Global:1;                 // 0 = Not global page, 1 = global page TLB not cleared on CR3 write
+    UINT64  Global:1;                 // 0 = Not global page, 1 = global page
+                                      //   TLB not cleared on CR3 write
     UINT64  Available:3;              // Available for use by system software
     UINT64  PAT:1;                    //
     UINT64  MustBeZero:17;            // Must be zero;
     UINT64  PageTableBaseAddress:22;  // Page Table Base Address
     UINT64  AvabilableHigh:11;        // Available for use by system software
-    UINT64  Nx:1;                     // 0 = Execute Code, 1 = No Code Execution
+    UINT64  Nx:1;                     // 0 = Execute Code,
+                                      //   1 = No Code Execution
   } Bits;
   UINT64    Uint64;
 } PAGE_TABLE_1G_ENTRY;
 
 #pragma pack()
 
 #define IA32_PG_P                   BIT0
 #define IA32_PG_RW                  BIT1
 #define IA32_PG_PS                  BIT7
 
 #define PAGING_PAE_INDEX_MASK       0x1FF
 
 #define PAGING_4K_ADDRESS_MASK_64   0x000FFFFFFFFFF000ull
 #define PAGING_2M_ADDRESS_MASK_64   0x000FFFFFFFE00000ull
 #define PAGING_1G_ADDRESS_MASK_64   0x000FFFFFC0000000ull
 
 #define PAGING_L1_ADDRESS_SHIFT     12
 #define PAGING_L2_ADDRESS_SHIFT     21
 #define PAGING_L3_ADDRESS_SHIFT     30
 #define PAGING_L4_ADDRESS_SHIFT     39
 
 #define PAGING_PML4E_NUMBER         4
 
 #define PAGETABLE_ENTRY_MASK        ((1UL << 9) - 1)
 #define PML4_OFFSET(x)              ( (x >> 39) & PAGETABLE_ENTRY_MASK)
 #define PDP_OFFSET(x)               ( (x >> 30) & PAGETABLE_ENTRY_MASK)
 #define PDE_OFFSET(x)               ( (x >> 21) & PAGETABLE_ENTRY_MASK)
 #define PTE_OFFSET(x)               ( (x >> 12) & PAGETABLE_ENTRY_MASK)
 #define PAGING_1G_ADDRESS_MASK_64   0x000FFFFFC0000000ull
 
 #define PAGE_TABLE_POOL_ALIGNMENT   BASE_2MB
 #define PAGE_TABLE_POOL_UNIT_SIZE   SIZE_2MB
-#define PAGE_TABLE_POOL_UNIT_PAGES  EFI_SIZE_TO_PAGES (PAGE_TABLE_POOL_UNIT_SIZE)
+#define PAGE_TABLE_POOL_UNIT_PAGES  \
+  EFI_SIZE_TO_PAGES (PAGE_TABLE_POOL_UNIT_SIZE)
 #define PAGE_TABLE_POOL_ALIGN_MASK  \
   (~(EFI_PHYSICAL_ADDRESS)(PAGE_TABLE_POOL_ALIGNMENT - 1))
 
 typedef struct {
   VOID            *NextPool;
   UINTN           Offset;
   UINTN           FreePages;
 } PAGE_TABLE_POOL;
 
 
 
 /**
-  This function clears memory encryption bit for the memory region specified by PhysicalAddress
-  and length from the current page table context.
+  This function clears memory encryption bit for the memory region specified by
+  PhysicalAddress and length from the current page table context.
 
-  @param[in]  PhysicalAddress         The physical address that is the start address of a memory region.
+  @param[in]  PhysicalAddress         The physical address that is the start
+                                      address of a memory region.
   @param[in]  Length                  The length of memory region
-  @param[in]  Flush                   Flush the caches before applying the encryption mask
+  @param[in]  Flush                   Flush the caches before applying the
+                                      encryption mask
 
-  @retval RETURN_SUCCESS              The attributes were cleared for the memory region.
+  @retval RETURN_SUCCESS              The attributes were cleared for the
+                                      memory region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
-  @retval RETURN_UNSUPPORTED          Setting the memory encyrption attribute is not supported
+  @retval RETURN_UNSUPPORTED          Setting the memory encyrption attribute
+                                      is not supported
 **/
 RETURN_STATUS
 EFIAPI
 InternalMemEncryptSevSetMemoryDecrypted (
   IN  PHYSICAL_ADDRESS     Cr3BaseAddress,
   IN  PHYSICAL_ADDRESS     PhysicalAddress,
   IN  UINT64               Length,
   IN  BOOLEAN              CacheFlush
   );
 
 /**
   This function sets memory encryption bit for the memory region specified by
   PhysicalAddress and length from the current page table context.
 
-  @param[in]  PhysicalAddress         The physical address that is the start address
-                                      of a memory region.
+  @param[in]  PhysicalAddress         The physical address that is the start
+                                      address of a memory region.
   @param[in]  Length                  The length of memory region
   @param[in]  Flush                   Flush the caches before applying the
                                       encryption mask
 
-  @retval RETURN_SUCCESS              The attributes were cleared for the memory region.
+  @retval RETURN_SUCCESS              The attributes were cleared for the
+                                      memory region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
-  @retval RETURN_UNSUPPORTED          Setting the memory encyrption attribute is
-                                      not supported
+  @retval RETURN_UNSUPPORTED          Setting the memory encyrption attribute
+                                      is not supported
 **/
 RETURN_STATUS
 EFIAPI
 InternalMemEncryptSevSetMemoryEncrypted (
   IN  PHYSICAL_ADDRESS     Cr3BaseAddress,
   IN  PHYSICAL_ADDRESS     PhysicalAddress,
   IN  UINT64               Length,
   IN  BOOLEAN              CacheFlush
   );
 
 #endif
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c b/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c
index a2ea99019917..d1130df2d0e7 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c
@@ -1,84 +1,90 @@
 /** @file
 
   Secure Encrypted Virtualization (SEV) library helper function
 
   Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
 
-  This program and the accompanying materials
-  are licensed and made available under the terms and conditions of the BSD
-  License which accompanies this distribution.  The full text of the license may
-  be found at http://opensource.org/licenses/bsd-license.php
+  This program and the accompanying materials are licensed and made available
+  under the terms and conditions of the BSD License which accompanies this
+  distribution.  The full text of the license may be found at
+  http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
   WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
 **/
 
 #include <Library/BaseLib.h>
 #include <Library/DebugLib.h>
 #include <Register/Cpuid.h>
 #include <Register/Amd/Cpuid.h>
 #include <Register/Amd/Msr.h>
 #include <Library/MemEncryptSevLib.h>
 
 /**
   This function clears memory encryption bit for the memory region specified
   by BaseAddress and Number of pages from the current page table context.
 
-  @param[in]  Cr3BaseAddress        Cr3 Base Address (if zero then use current CR3)
-  @param[in]  BaseAddress           The physical address that is the start address
-                                    of a memory region.
-  @param[in]  NumberOfPages         The number of pages from start memory region.
+  @param[in]  Cr3BaseAddress        Cr3 Base Address (if zero then use current
+                                    CR3)
+  @param[in]  BaseAddress           The physical address that is the start
+                                    address of a memory region.
+  @param[in]  NumberOfPages         The number of pages from start memory
+                                    region.
   @param[in]  Flush                 Flush the caches before clearing the bit
                                     (mostly TRUE except MMIO addresses)
 
-  @retval RETURN_SUCCESS            The attributes were cleared for the memory region.
+  @retval RETURN_SUCCESS            The attributes were cleared for the memory
+                                    region.
   @retval RETURN_INVALID_PARAMETER  Number of pages is zero.
   @retval RETURN_UNSUPPORTED        Clearing memory encryption attribute is not
                                     supported
   **/
 RETURN_STATUS
 EFIAPI
 MemEncryptSevClearPageEncMask (
   IN PHYSICAL_ADDRESS         Cr3BaseAddress,
   IN PHYSICAL_ADDRESS         BaseAddress,
   IN UINTN                    NumberOfPages,
   IN BOOLEAN                  Flush
   )
 {
   //
   // Memory encryption bit is not accessible in 32-bit mode
   //
   return RETURN_UNSUPPORTED;
 }
 
 /**
   This function sets memory encryption bit for the memory region specified by
   BaseAddress and Number of pages from the current page table context.
 
-  @param[in]  Cr3BaseAddress        Cr3 Base Address (if zero then use current CR3)
-  @param[in]  BaseAddress           The physical address that is the start address
-                                    of a memory region.
-  @param[in]  NumberOfPages         The number of pages from start memory region.
+  @param[in]  Cr3BaseAddress        Cr3 Base Address (if zero then use current
+                                    CR3)
+  @param[in]  BaseAddress           The physical address that is the start
+                                    address of a memory region.
+  @param[in]  NumberOfPages         The number of pages from start memory
+                                    region.
   @param[in]  Flush                 Flush the caches before clearing the bit
                                     (mostly TRUE except MMIO addresses)
 
-  @retval RETURN_SUCCESS            The attributes were set for the memory region.
+  @retval RETURN_SUCCESS            The attributes were set for the memory
+                                    region.
   @retval RETURN_INVALID_PARAMETER  Number of pages is zero.
   @retval RETURN_UNSUPPORTED        Clearing memory encryption attribute is not
                                     supported
   **/
 RETURN_STATUS
 EFIAPI
 MemEncryptSevSetPageEncMask (
   IN PHYSICAL_ADDRESS         Cr3BaseAddress,
   IN PHYSICAL_ADDRESS         BaseAddress,
   IN UINTN                    NumberOfPages,
   IN BOOLEAN                  Flush
   )
 {
   //
   // Memory encryption bit is not accessible in 32-bit mode
   //
   return RETURN_UNSUPPORTED;
 }
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c b/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c
index 002f079c7eb3..ff561236d819 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c
@@ -1,30 +1,30 @@
 /** @file
 
   Secure Encrypted Virtualization (SEV) library helper function
 
   Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
 
-  This program and the accompanying materials
-  are licensed and made available under the terms and conditions of the BSD
-  License which accompanies this distribution.  The full text of the license may
-  be found at http://opensource.org/licenses/bsd-license.php
+  This program and the accompanying materials are licensed and made available
+  under the terms and conditions of the BSD License which accompanies this
+  distribution.  The full text of the license may be found at
+  http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
   WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
 **/
 
 #include <Library/BaseLib.h>
 #include <Library/DebugLib.h>
 #include <Register/Cpuid.h>
 #include <Register/Amd/Cpuid.h>
 #include <Register/Amd/Msr.h>
 #include <Library/MemEncryptSevLib.h>
 
 STATIC BOOLEAN mSevStatus = FALSE;
 STATIC BOOLEAN mSevStatusChecked = FALSE;
 
 /**
 
   Returns a boolean to indicate whether SEV is enabled
 
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c
index 9ec76708bd7b..4b7fdf7d044d 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c
@@ -1,84 +1,98 @@
 /** @file
 
   Secure Encrypted Virtualization (SEV) library helper function
 
   Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
 
-  This program and the accompanying materials
-  are licensed and made available under the terms and conditions of the BSD
-  License which accompanies this distribution.  The full text of the license may
-  be found at http://opensource.org/licenses/bsd-license.php
+  This program and the accompanying materials are licensed and made available
+  under the terms and conditions of the BSD License which accompanies this
+  distribution.  The full text of the license may be found at
+  http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
   WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
 **/
 
 #include <Library/BaseLib.h>
 #include <Library/DebugLib.h>
 #include <Register/Cpuid.h>
 #include <Register/Amd/Cpuid.h>
 #include <Register/Amd/Msr.h>
 #include <Library/MemEncryptSevLib.h>
 
 #include "VirtualMemory.h"
 
 /**
 
   This function clears memory encryption bit for the memory region specified by
   BaseAddress and Number of pages from the current page table context.
 
-  @param[in]  Cr3BaseAddress          Cr3 Base Address (if zero then use current CR3)
-  @param[in]  BaseAddress             The physical address that is the start address
-                                      of a memory region.
-  @param[in]  NumberOfPages           The number of pages from start memory region.
+  @param[in]  Cr3BaseAddress          Cr3 Base Address (if zero then use
+                                      current CR3)
+  @param[in]  BaseAddress             The physical address that is the start
+                                      address of a memory region.
+  @param[in]  NumberOfPages           The number of pages from start memory
+                                      region.
   @param[in]  Flush                   Flush the caches before clearing the bit
                                       (mostly TRUE except MMIO addresses)
 
-  @retval RETURN_SUCCESS              The attributes were cleared for the memory
-                                      region.
+  @retval RETURN_SUCCESS              The attributes were cleared for the
+                                      memory region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
-  @retval RETURN_UNSUPPORTED          Clearing the memory encryption attribute is
-                                      not supported
+  @retval RETURN_UNSUPPORTED          Clearing the memory encryption attribute
+                                      is not supported
   **/
 RETURN_STATUS
 EFIAPI
 MemEncryptSevClearPageEncMask (
   IN PHYSICAL_ADDRESS         Cr3BaseAddress,
   IN PHYSICAL_ADDRESS         BaseAddress,
   IN UINTN                    NumPages,
   IN BOOLEAN                  Flush
   )
 {
-  return InternalMemEncryptSevSetMemoryDecrypted (Cr3BaseAddress, BaseAddress, EFI_PAGES_TO_SIZE(NumPages), Flush);
+  return InternalMemEncryptSevSetMemoryDecrypted (
+           Cr3BaseAddress,
+           BaseAddress,
+           EFI_PAGES_TO_SIZE (NumPages),
+           Flush
+           );
 }
 
 /**
 
   This function clears memory encryption bit for the memory region specified by
   BaseAddress and Number of pages from the current page table context.
 
-  @param[in]  Cr3BaseAddress          Cr3 Base Address (if zero then use current CR3)
-  @param[in]  BaseAddress             The physical address that is the start address
-                                      of a memory region.
-  @param[in]  NumberOfPages           The number of pages from start memory region.
+  @param[in]  Cr3BaseAddress          Cr3 Base Address (if zero then use
+                                      current CR3)
+  @param[in]  BaseAddress             The physical address that is the start
+                                      address of a memory region.
+  @param[in]  NumberOfPages           The number of pages from start memory
+                                      region.
   @param[in]  Flush                   Flush the caches before clearing the bit
                                       (mostly TRUE except MMIO addresses)
 
-  @retval RETURN_SUCCESS              The attributes were cleared for the memory
-                                      region.
+  @retval RETURN_SUCCESS              The attributes were cleared for the
+                                      memory region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
-  @retval RETURN_UNSUPPORTED          Clearing the memory encryption attribute is
-                                      not supported
+  @retval RETURN_UNSUPPORTED          Clearing the memory encryption attribute
+                                      is not supported
   **/
 RETURN_STATUS
 EFIAPI
 MemEncryptSevSetPageEncMask (
   IN PHYSICAL_ADDRESS         Cr3BaseAddress,
   IN PHYSICAL_ADDRESS         BaseAddress,
   IN UINTN                    NumPages,
   IN BOOLEAN                  Flush
   )
 {
-  return InternalMemEncryptSevSetMemoryEncrypted (Cr3BaseAddress, BaseAddress, EFI_PAGES_TO_SIZE(NumPages), Flush);
+  return InternalMemEncryptSevSetMemoryEncrypted (
+           Cr3BaseAddress,
+           BaseAddress,
+           EFI_PAGES_TO_SIZE (NumPages),
+           Flush
+           );
 }
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
index 4185874c99b8..65b8babaac44 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
@@ -1,36 +1,36 @@
 /** @file
 
   Virtual Memory Management Services to set or clear the memory encryption bit
 
-Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>
-Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
+  Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>
+  Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
 
-This program and the accompanying materials
-are licensed and made available under the terms and conditions of the BSD License
-which accompanies this distribution.  The full text of the license may be found at
-http://opensource.org/licenses/bsd-license.php
+  This program and the accompanying materials are licensed and made available
+  under the terms and conditions of the BSD License which accompanies this
+  distribution.  The full text of the license may be found at
+  http://opensource.org/licenses/bsd-license.php
 
-THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT
+  WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
-Code is derived from MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c
+  Code is derived from MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c
 
 **/
 
 #include <Library/CpuLib.h>
 #include <Register/Cpuid.h>
 #include <Register/Amd/Cpuid.h>
 
 #include "VirtualMemory.h"
 
 STATIC BOOLEAN mAddressEncMaskChecked = FALSE;
 STATIC UINT64  mAddressEncMask;
 STATIC PAGE_TABLE_POOL   *mPageTablePool = NULL;
 
 typedef enum {
    SetCBit,
    ClearCBit
 } MAP_RANGE_MODE;
 
 /**
   Get the memory encryption mask
@@ -52,45 +52,46 @@ GetMemEncryptionAddressMask (
   }
 
   //
   // CPUID Fn8000_001F[EBX] Bit 0:5 (memory encryption bit position)
   //
   AsmCpuid (CPUID_MEMORY_ENCRYPTION_INFO, NULL, &Ebx.Uint32, NULL, NULL);
   EncryptionMask = LShiftU64 (1, Ebx.Bits.PtePosBits);
 
   mAddressEncMask = EncryptionMask & PAGING_1G_ADDRESS_MASK_64;
   mAddressEncMaskChecked = TRUE;
 
   return mAddressEncMask;
 }
 
 /**
   Initialize a buffer pool for page table use only.
 
   To reduce the potential split operation on page table, the pages reserved for
   page table should be allocated in the times of PAGE_TABLE_POOL_UNIT_PAGES and
   at the boundary of PAGE_TABLE_POOL_ALIGNMENT. So the page pool is always
-  initialized with number of pages greater than or equal to the given PoolPages.
+  initialized with number of pages greater than or equal to the given
+  PoolPages.
 
   Once the pages in the pool are used up, this method should be called again to
-  reserve at least another PAGE_TABLE_POOL_UNIT_PAGES. Usually this won't happen
-  often in practice.
+  reserve at least another PAGE_TABLE_POOL_UNIT_PAGES. Usually this won't
+  happen often in practice.
 
   @param[in] PoolPages      The least page number of the pool to be created.
 
   @retval TRUE    The pool is initialized successfully.
   @retval FALSE   The memory is out of resource.
 **/
 STATIC
 BOOLEAN
 InitializePageTablePool (
   IN  UINTN                           PoolPages
   )
 {
   VOID                      *Buffer;
 
   //
   // Always reserve at least PAGE_TABLE_POOL_UNIT_PAGES, including one page for
   // header.
   //
   PoolPages += 1;   // Add one page for header.
   PoolPages = ((PoolPages - 1) / PAGE_TABLE_POOL_UNIT_PAGES + 1) *
@@ -166,89 +167,96 @@ AllocatePageTableMemory (
 
   mPageTablePool->Offset     += EFI_PAGES_TO_SIZE (Pages);
   mPageTablePool->FreePages  -= Pages;
 
   DEBUG ((
     DEBUG_VERBOSE,
     "%a:%a: Buffer=0x%Lx Pages=%ld\n",
     gEfiCallerBaseName,
     __FUNCTION__,
     Buffer,
     Pages
     ));
 
   return Buffer;
 }
 
 
 /**
   Split 2M page to 4K.
 
-  @param[in]      PhysicalAddress       Start physical address the 2M page covered.
+  @param[in]      PhysicalAddress       Start physical address the 2M page
+                                        covered.
   @param[in, out] PageEntry2M           Pointer to 2M page entry.
   @param[in]      StackBase             Stack base address.
   @param[in]      StackSize             Stack size.
 
 **/
 STATIC
 VOID
 Split2MPageTo4K (
   IN        PHYSICAL_ADDRESS               PhysicalAddress,
   IN  OUT   UINT64                        *PageEntry2M,
   IN        PHYSICAL_ADDRESS               StackBase,
   IN        UINTN                          StackSize
   )
 {
   PHYSICAL_ADDRESS                  PhysicalAddress4K;
   UINTN                             IndexOfPageTableEntries;
   PAGE_TABLE_4K_ENTRY               *PageTableEntry, *PageTableEntry1;
   UINT64                            AddressEncMask;
 
   PageTableEntry = AllocatePageTableMemory(1);
 
   PageTableEntry1 = PageTableEntry;
 
   AddressEncMask = GetMemEncryptionAddressMask ();
 
   ASSERT (PageTableEntry != NULL);
   ASSERT (*PageEntry2M & AddressEncMask);
 
   PhysicalAddress4K = PhysicalAddress;
-  for (IndexOfPageTableEntries = 0; IndexOfPageTableEntries < 512; IndexOfPageTableEntries++, PageTableEntry++, PhysicalAddress4K += SIZE_4KB) {
+  for (IndexOfPageTableEntries = 0;
+       IndexOfPageTableEntries < 512;
+       (IndexOfPageTableEntries++,
+        PageTableEntry++,
+        PhysicalAddress4K += SIZE_4KB)) {
     //
     // Fill in the Page Table entries
     //
     PageTableEntry->Uint64 = (UINT64) PhysicalAddress4K | AddressEncMask;
     PageTableEntry->Bits.ReadWrite = 1;
     PageTableEntry->Bits.Present = 1;
-    if ((PhysicalAddress4K >= StackBase) && (PhysicalAddress4K < StackBase + StackSize)) {
+    if ((PhysicalAddress4K >= StackBase) &&
+        (PhysicalAddress4K < StackBase + StackSize)) {
       //
       // Set Nx bit for stack.
       //
       PageTableEntry->Bits.Nx = 1;
     }
   }
 
   //
   // Fill in 2M page entry.
   //
-  *PageEntry2M = (UINT64) (UINTN) PageTableEntry1 | IA32_PG_P | IA32_PG_RW | AddressEncMask;
+  *PageEntry2M = ((UINT64)(UINTN)PageTableEntry1 |
+                  IA32_PG_P | IA32_PG_RW | AddressEncMask);
 }
 
 /**
   Set one page of page table pool memory to be read-only.
 
   @param[in] PageTableBase    Base address of page table (CR3).
   @param[in] Address          Start address of a page to be set as read-only.
   @param[in] Level4Paging     Level 4 paging flag.
 
 **/
 STATIC
 VOID
 SetPageTablePoolReadOnly (
   IN  UINTN                             PageTableBase,
   IN  EFI_PHYSICAL_ADDRESS              Address,
   IN  BOOLEAN                           Level4Paging
   )
 {
   UINTN                 Index;
   UINTN                 EntryIndex;
@@ -374,96 +382,108 @@ EnablePageTableProtection (
   PAGE_TABLE_POOL         *HeadPool;
   PAGE_TABLE_POOL         *Pool;
   UINT64                  PoolSize;
   EFI_PHYSICAL_ADDRESS    Address;
 
   if (mPageTablePool == NULL) {
     return;
   }
 
   //
   // SetPageTablePoolReadOnly might update mPageTablePool. It's safer to
   // remember original one in advance.
   //
   HeadPool = mPageTablePool;
   Pool = HeadPool;
   do {
     Address  = (EFI_PHYSICAL_ADDRESS)(UINTN)Pool;
     PoolSize = Pool->Offset + EFI_PAGES_TO_SIZE (Pool->FreePages);
 
     //
-    // The size of one pool must be multiple of PAGE_TABLE_POOL_UNIT_SIZE, which
-    // is one of page size of the processor (2MB by default). Let's apply the
-    // protection to them one by one.
+    // The size of one pool must be multiple of PAGE_TABLE_POOL_UNIT_SIZE,
+    // which is one of page size of the processor (2MB by default). Let's apply
+    // the protection to them one by one.
     //
     while (PoolSize > 0) {
       SetPageTablePoolReadOnly(PageTableBase, Address, Level4Paging);
       Address   += PAGE_TABLE_POOL_UNIT_SIZE;
       PoolSize  -= PAGE_TABLE_POOL_UNIT_SIZE;
     }
 
     Pool = Pool->NextPool;
   } while (Pool != HeadPool);
 
 }
 
 
 /**
   Split 1G page to 2M.
 
-  @param[in]      PhysicalAddress       Start physical address the 1G page covered.
+  @param[in]      PhysicalAddress       Start physical address the 1G page
+                                        covered.
   @param[in, out] PageEntry1G           Pointer to 1G page entry.
   @param[in]      StackBase             Stack base address.
   @param[in]      StackSize             Stack size.
 
 **/
 STATIC
 VOID
 Split1GPageTo2M (
   IN          PHYSICAL_ADDRESS               PhysicalAddress,
   IN  OUT     UINT64                         *PageEntry1G,
   IN          PHYSICAL_ADDRESS               StackBase,
   IN          UINTN                          StackSize
   )
 {
   PHYSICAL_ADDRESS                  PhysicalAddress2M;
   UINTN                             IndexOfPageDirectoryEntries;
   PAGE_TABLE_ENTRY                  *PageDirectoryEntry;
   UINT64                            AddressEncMask;
 
   PageDirectoryEntry = AllocatePageTableMemory(1);
 
   AddressEncMask = GetMemEncryptionAddressMask ();
   ASSERT (PageDirectoryEntry != NULL);
   ASSERT (*PageEntry1G & GetMemEncryptionAddressMask ());
   //
   // Fill in 1G page entry.
   //
-  *PageEntry1G = (UINT64) (UINTN) PageDirectoryEntry | IA32_PG_P | IA32_PG_RW | AddressEncMask;
+  *PageEntry1G = ((UINT64)(UINTN)PageDirectoryEntry |
+                  IA32_PG_P | IA32_PG_RW | AddressEncMask);
 
   PhysicalAddress2M = PhysicalAddress;
-  for (IndexOfPageDirectoryEntries = 0; IndexOfPageDirectoryEntries < 512; IndexOfPageDirectoryEntries++, PageDirectoryEntry++, PhysicalAddress2M += SIZE_2MB) {
-    if ((PhysicalAddress2M < StackBase + StackSize) && ((PhysicalAddress2M + SIZE_2MB) > StackBase)) {
+  for (IndexOfPageDirectoryEntries = 0;
+       IndexOfPageDirectoryEntries < 512;
+       (IndexOfPageDirectoryEntries++,
+        PageDirectoryEntry++,
+        PhysicalAddress2M += SIZE_2MB)) {
+    if ((PhysicalAddress2M < StackBase + StackSize) &&
+        ((PhysicalAddress2M + SIZE_2MB) > StackBase)) {
       //
       // Need to split this 2M page that covers stack range.
       //
-      Split2MPageTo4K (PhysicalAddress2M, (UINT64 *) PageDirectoryEntry, StackBase, StackSize);
+      Split2MPageTo4K (
+        PhysicalAddress2M,
+        (UINT64 *)PageDirectoryEntry,
+        StackBase,
+        StackSize
+        );
     } else {
       //
       // Fill in the Page Directory entries
       //
       PageDirectoryEntry->Uint64 = (UINT64) PhysicalAddress2M | AddressEncMask;
       PageDirectoryEntry->Bits.ReadWrite = 1;
       PageDirectoryEntry->Bits.Present = 1;
       PageDirectoryEntry->Bits.MustBe1 = 1;
     }
   }
 }
 
 
 /**
   Set or Clear the memory encryption bit
 
   @param[in]      PagetablePoint        Page table entry pointer (PTE).
   @param[in]      Mode                  Set or Clear encryption bit
 
 **/
@@ -510,62 +530,63 @@ VOID
 DisableReadOnlyPageWriteProtect (
   VOID
   )
 {
   AsmWriteCr0 (AsmReadCr0() & ~BIT16);
 }
 
 /**
  Enable Write Protect on pages marked as read-only.
 **/
 VOID
 EnableReadOnlyPageWriteProtect (
   VOID
   )
 {
   AsmWriteCr0 (AsmReadCr0() | BIT16);
 }
 
 
 /**
-  This function either sets or clears memory encryption bit for the memory region
-  specified by PhysicalAddress and length from the current page table context.
+  This function either sets or clears memory encryption bit for the memory
+  region specified by PhysicalAddress and length from the current page table
+  context.
 
   The function iterates through the physicalAddress one page at a time, and set
   or clears the memory encryption mask in the page table. If it encounters
   that a given physical address range is part of large page then it attempts to
   change the attribute at one go (based on size), otherwise it splits the
   large pages into smaller (e.g 2M page into 4K pages) and then try to set or
   clear the encryption bit on the smallest page size.
 
   @param[in]  PhysicalAddress         The physical address that is the start
                                       address of a memory region.
   @param[in]  Length                  The length of memory region
   @param[in]  Mode                    Set or Clear mode
   @param[in]  Flush                   Flush the caches before applying the
                                       encryption mask
 
-  @retval RETURN_SUCCESS              The attributes were cleared for the memory
-                                      region.
+  @retval RETURN_SUCCESS              The attributes were cleared for the
+                                      memory region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
-  @retval RETURN_UNSUPPORTED          Setting the memory encyrption attribute is
-                                      not supported
+  @retval RETURN_UNSUPPORTED          Setting the memory encyrption attribute
+                                      is not supported
 **/
 
 STATIC
 RETURN_STATUS
 EFIAPI
 SetMemoryEncDec (
   IN    PHYSICAL_ADDRESS         Cr3BaseAddress,
   IN    PHYSICAL_ADDRESS         PhysicalAddress,
   IN    UINTN                    Length,
   IN    MAP_RANGE_MODE           Mode,
   IN    BOOLEAN                  CacheFlush
   )
 {
   PAGE_MAP_AND_DIRECTORY_POINTER *PageMapLevel4Entry;
   PAGE_MAP_AND_DIRECTORY_POINTER *PageUpperDirectoryPointerEntry;
   PAGE_MAP_AND_DIRECTORY_POINTER *PageDirectoryPointerEntry;
   PAGE_TABLE_1G_ENTRY            *PageDirectory1GEntry;
   PAGE_TABLE_ENTRY               *PageDirectory2MEntry;
   PAGE_TABLE_4K_ENTRY            *PageTableEntry;
   UINT64                         PgTableMask;
@@ -584,81 +605,84 @@ SetMemoryEncDec (
     (Mode == SetCBit) ? "Encrypt" : "Decrypt",
     (UINT32)CacheFlush
     ));
 
   //
   // Check if we have a valid memory encryption mask
   //
   AddressEncMask = GetMemEncryptionAddressMask ();
   if (!AddressEncMask) {
     return RETURN_ACCESS_DENIED;
   }
 
   PgTableMask = AddressEncMask | EFI_PAGE_MASK;
 
   if (Length == 0) {
     return RETURN_INVALID_PARAMETER;
   }
 
   //
   // We are going to change the memory encryption attribute from C=0 -> C=1 or
-  // vice versa Flush the caches to ensure that data is written into memory with
-  // correct C-bit
+  // vice versa Flush the caches to ensure that data is written into memory
+  // with correct C-bit
   //
   if (CacheFlush) {
     WriteBackInvalidateDataCacheRange((VOID*) (UINTN)PhysicalAddress, Length);
   }
 
   //
   // Make sure that the page table is changeable.
   //
   IsWpEnabled = IsReadOnlyPageWriteProtected ();
   if (IsWpEnabled) {
     DisableReadOnlyPageWriteProtect ();
   }
 
   Status = EFI_SUCCESS;
 
   while (Length)
   {
     //
     // If Cr3BaseAddress is not specified then read the current CR3
     //
     if (Cr3BaseAddress == 0) {
       Cr3BaseAddress = AsmReadCr3();
     }
 
     PageMapLevel4Entry = (VOID*) (Cr3BaseAddress & ~PgTableMask);
     PageMapLevel4Entry += PML4_OFFSET(PhysicalAddress);
     if (!PageMapLevel4Entry->Bits.Present) {
       DEBUG ((
         DEBUG_ERROR,
         "%a:%a: bad PML4 for Physical=0x%Lx\n",
         gEfiCallerBaseName,
         __FUNCTION__,
         PhysicalAddress
         ));
       Status = RETURN_NO_MAPPING;
       goto Done;
     }
 
-    PageDirectory1GEntry = (VOID*) ((PageMapLevel4Entry->Bits.PageTableBaseAddress<<12) & ~PgTableMask);
+    PageDirectory1GEntry = (VOID *)(
+                             (PageMapLevel4Entry->Bits.PageTableBaseAddress <<
+                              12) & ~PgTableMask
+                             );
     PageDirectory1GEntry += PDP_OFFSET(PhysicalAddress);
     if (!PageDirectory1GEntry->Bits.Present) {
       DEBUG ((
         DEBUG_ERROR,
         "%a:%a: bad PDPE for Physical=0x%Lx\n",
         gEfiCallerBaseName,
         __FUNCTION__,
         PhysicalAddress
         ));
       Status = RETURN_NO_MAPPING;
       goto Done;
     }
 
     //
     // If the MustBe1 bit is not 1, it's not actually a 1GB entry
     //
     if (PageDirectory1GEntry->Bits.MustBe1) {
       //
       // Valid 1GB page
       // If we have at least 1GB to go, we can just update this entry
@@ -668,90 +692,110 @@ SetMemoryEncDec (
         DEBUG ((
           DEBUG_VERBOSE,
           "%a:%a: updated 1GB entry for Physical=0x%Lx\n",
           gEfiCallerBaseName,
           __FUNCTION__,
           PhysicalAddress
           ));
         PhysicalAddress += BIT30;
         Length -= BIT30;
       } else {
         //
         // We must split the page
         //
         DEBUG ((
           DEBUG_VERBOSE,
           "%a:%a: splitting 1GB page for Physical=0x%Lx\n",
           gEfiCallerBaseName,
           __FUNCTION__,
           PhysicalAddress
           ));
-        Split1GPageTo2M(((UINT64)PageDirectory1GEntry->Bits.PageTableBaseAddress)<<30, (UINT64*) PageDirectory1GEntry, 0, 0);
+        Split1GPageTo2M (
+          (UINT64)PageDirectory1GEntry->Bits.PageTableBaseAddress << 30,
+          (UINT64 *)PageDirectory1GEntry,
+          0,
+          0
+          );
         continue;
       }
     } else {
       //
       // Actually a PDP
       //
-      PageUpperDirectoryPointerEntry = (PAGE_MAP_AND_DIRECTORY_POINTER*) PageDirectory1GEntry;
-      PageDirectory2MEntry = (VOID*) ((PageUpperDirectoryPointerEntry->Bits.PageTableBaseAddress<<12) & ~PgTableMask);
+      PageUpperDirectoryPointerEntry =
+        (PAGE_MAP_AND_DIRECTORY_POINTER *)PageDirectory1GEntry;
+      PageDirectory2MEntry =
+        (VOID *)(
+          (PageUpperDirectoryPointerEntry->Bits.PageTableBaseAddress <<
+           12) & ~PgTableMask
+          );
       PageDirectory2MEntry += PDE_OFFSET(PhysicalAddress);
       if (!PageDirectory2MEntry->Bits.Present) {
         DEBUG ((
           DEBUG_ERROR,
           "%a:%a: bad PDE for Physical=0x%Lx\n",
           gEfiCallerBaseName,
           __FUNCTION__,
           PhysicalAddress
           ));
         Status = RETURN_NO_MAPPING;
         goto Done;
       }
       //
       // If the MustBe1 bit is not a 1, it's not a 2MB entry
       //
       if (PageDirectory2MEntry->Bits.MustBe1) {
         //
         // Valid 2MB page
         // If we have at least 2MB left to go, we can just update this entry
         //
         if (!(PhysicalAddress & (BIT21-1)) && Length >= BIT21) {
           SetOrClearCBit (&PageDirectory2MEntry->Uint64, Mode);
           PhysicalAddress += BIT21;
           Length -= BIT21;
         } else {
           //
           // We must split up this page into 4K pages
           //
           DEBUG ((
             DEBUG_VERBOSE,
             "%a:%a: splitting 2MB page for Physical=0x%Lx\n",
             gEfiCallerBaseName,
             __FUNCTION__,
             PhysicalAddress
             ));
-          Split2MPageTo4K (((UINT64)PageDirectory2MEntry->Bits.PageTableBaseAddress) << 21, (UINT64*) PageDirectory2MEntry, 0, 0);
+          Split2MPageTo4K (
+            (UINT64)PageDirectory2MEntry->Bits.PageTableBaseAddress << 21,
+            (UINT64 *)PageDirectory2MEntry,
+            0,
+            0
+            );
           continue;
         }
       } else {
-        PageDirectoryPointerEntry = (PAGE_MAP_AND_DIRECTORY_POINTER*) PageDirectory2MEntry;
-        PageTableEntry = (VOID*) (PageDirectoryPointerEntry->Bits.PageTableBaseAddress<<12 & ~PgTableMask);
+        PageDirectoryPointerEntry =
+          (PAGE_MAP_AND_DIRECTORY_POINTER *)PageDirectory2MEntry;
+        PageTableEntry =
+          (VOID *)(
+            (PageDirectoryPointerEntry->Bits.PageTableBaseAddress <<
+             12) & ~PgTableMask
+            );
         PageTableEntry += PTE_OFFSET(PhysicalAddress);
         if (!PageTableEntry->Bits.Present) {
           DEBUG ((
             DEBUG_ERROR,
             "%a:%a: bad PTE for Physical=0x%Lx\n",
             gEfiCallerBaseName,
             __FUNCTION__,
             PhysicalAddress
             ));
           Status = RETURN_NO_MAPPING;
           goto Done;
         }
         SetOrClearCBit (&PageTableEntry->Uint64, Mode);
         PhysicalAddress += EFI_PAGE_SIZE;
         Length -= EFI_PAGE_SIZE;
       }
     }
   }
 
   //
@@ -771,66 +815,78 @@ Done:
   //
   // Restore page table write protection, if any.
   //
   if (IsWpEnabled) {
     EnableReadOnlyPageWriteProtect ();
   }
 
   return Status;
 }
 
 /**
   This function clears memory encryption bit for the memory region specified by
   PhysicalAddress and length from the current page table context.
 
   @param[in]  PhysicalAddress         The physical address that is the start
                                       address of a memory region.
   @param[in]  Length                  The length of memory region
   @param[in]  Flush                   Flush the caches before applying the
                                       encryption mask
 
-  @retval RETURN_SUCCESS              The attributes were cleared for the memory
-                                      region.
+  @retval RETURN_SUCCESS              The attributes were cleared for the
+                                      memory region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
-  @retval RETURN_UNSUPPORTED          Setting the memory encyrption attribute is
-                                      not supported
+  @retval RETURN_UNSUPPORTED          Setting the memory encyrption attribute
+                                      is not supported
 **/
 RETURN_STATUS
 EFIAPI
 InternalMemEncryptSevSetMemoryDecrypted (
   IN  PHYSICAL_ADDRESS        Cr3BaseAddress,
   IN  PHYSICAL_ADDRESS        PhysicalAddress,
   IN  UINTN                   Length,
   IN  BOOLEAN                 Flush
   )
 {
 
-  return SetMemoryEncDec (Cr3BaseAddress, PhysicalAddress, Length, ClearCBit, Flush);
+  return SetMemoryEncDec (
+           Cr3BaseAddress,
+           PhysicalAddress,
+           Length,
+           ClearCBit,
+           Flush
+           );
 }
 
 /**
   This function sets memory encryption bit for the memory region specified by
   PhysicalAddress and length from the current page table context.
 
-  @param[in]  PhysicalAddress         The physical address that is the start address
-                                      of a memory region.
+  @param[in]  PhysicalAddress         The physical address that is the start
+                                      address of a memory region.
   @param[in]  Length                  The length of memory region
   @param[in]  Flush                   Flush the caches before applying the
                                       encryption mask
 
-  @retval RETURN_SUCCESS              The attributes were cleared for the memory
-                                      region.
+  @retval RETURN_SUCCESS              The attributes were cleared for the
+                                      memory region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
-  @retval RETURN_UNSUPPORTED          Setting the memory encyrption attribute is
-                                      not supported
+  @retval RETURN_UNSUPPORTED          Setting the memory encyrption attribute
+                                      is not supported
 **/
 RETURN_STATUS
 EFIAPI
 InternalMemEncryptSevSetMemoryEncrypted (
   IN  PHYSICAL_ADDRESS        Cr3BaseAddress,
   IN  PHYSICAL_ADDRESS        PhysicalAddress,
   IN  UINTN                   Length,
   IN  BOOLEAN                 Flush
   )
 {
-  return SetMemoryEncDec (Cr3BaseAddress, PhysicalAddress, Length, SetCBit, Flush);
+  return SetMemoryEncDec (
+           Cr3BaseAddress,
+           PhysicalAddress,
+           Length,
+           SetCBit,
+           Flush
+           );
 }
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 02/20] OvmfPkg/MemEncryptSevLib: clean up MemEncryptSevIsEnabled() decl
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
  2018-03-02  0:03 ` [PATCH 01/20] OvmfPkg/MemEncryptSevLib: rewrap to 79 characters width Laszlo Ersek
@ 2018-03-02  0:03 ` Laszlo Ersek
  2018-03-02  0:03 ` [PATCH 03/20] OvmfPkg/MemEncryptSevLib: clean up MemEncryptSevClearPageEncMask() decl Laszlo Ersek
                   ` (19 subsequent siblings)
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:03 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

The declaration and the definition(s) of the function should have
identical leading comments and/or identical parameter lists. Also remove
any excess space in the comment block, and unindent the trailing "**/" if
necessary.

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/Include/Library/MemEncryptSevLib.h                      | 4 ++--
 OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c | 3 +--
 2 files changed, 3 insertions(+), 4 deletions(-)

diff --git a/OvmfPkg/Include/Library/MemEncryptSevLib.h b/OvmfPkg/Include/Library/MemEncryptSevLib.h
index 4f3ba9f22cb4..88b272ebedef 100644
--- a/OvmfPkg/Include/Library/MemEncryptSevLib.h
+++ b/OvmfPkg/Include/Library/MemEncryptSevLib.h
@@ -5,43 +5,43 @@
   Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
 
   This program and the accompanying materials are licensed and made available
   under the terms and conditions of the BSD License which accompanies this
   distribution.  The full text of the license may be found at
   http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
   WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
 **/
 
 #ifndef _MEM_ENCRYPT_SEV_LIB_H_
 #define _MEM_ENCRYPT_SEV_LIB_H_
 
 #include <Base.h>
 
 /**
   Returns a boolean to indicate whether SEV is enabled
 
-  @retval TRUE           SEV is active
+  @retval TRUE           SEV is enabled
   @retval FALSE          SEV is not enabled
-  **/
+**/
 BOOLEAN
 EFIAPI
 MemEncryptSevIsEnabled (
   VOID
   );
 
 /**
   This function clears memory encryption bit for the memory region specified
   by BaseAddress and Number of pages from the current page table context.
 
   @param[in]  BaseAddress           The physical address that is the start
                                     address of a memory region.
   @param[in]  NumberOfPages         The number of pages from start memory
                                     region.
   @param[in]  Flush                 Flush the caches before clearing the bit
                                     (mostly TRUE except MMIO addresses)
 
   @retval RETURN_SUCCESS            The attributes were cleared for the memory
                                     region.
   @retval RETURN_INVALID_PARAMETER  Number of pages is zero.
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c b/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c
index ff561236d819..44c2c98a6afc 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c
@@ -50,41 +50,40 @@ InternalMemEncryptSevIsEnabled (
     //
     // CPUID Fn8000_001F[EAX] Bit 1 (Sev supported)
     //
     AsmCpuid (CPUID_MEMORY_ENCRYPTION_INFO, &Eax.Uint32, NULL, NULL, NULL);
 
     if (Eax.Bits.SevBit) {
       //
       // Check MSR_0xC0010131 Bit 0 (Sev Enabled)
       //
       Msr.Uint32 = AsmReadMsr32 (MSR_SEV_STATUS);
       if (Msr.Bits.SevBit) {
         return TRUE;
       }
     }
   }
 
   return FALSE;
 }
 
 /**
-
   Returns a boolean to indicate whether SEV is enabled
 
   @retval TRUE           SEV is enabled
   @retval FALSE          SEV is not enabled
-  **/
+**/
 BOOLEAN
 EFIAPI
 MemEncryptSevIsEnabled (
   VOID
   )
 {
   if (mSevStatusChecked) {
     return mSevStatus;
   }
 
   mSevStatus = InternalMemEncryptSevIsEnabled();
   mSevStatusChecked = TRUE;
 
   return mSevStatus;
 }
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 03/20] OvmfPkg/MemEncryptSevLib: clean up MemEncryptSevClearPageEncMask() decl
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
  2018-03-02  0:03 ` [PATCH 01/20] OvmfPkg/MemEncryptSevLib: rewrap to 79 characters width Laszlo Ersek
  2018-03-02  0:03 ` [PATCH 02/20] OvmfPkg/MemEncryptSevLib: clean up MemEncryptSevIsEnabled() decl Laszlo Ersek
@ 2018-03-02  0:03 ` Laszlo Ersek
  2018-03-02  0:03 ` [PATCH 04/20] OvmfPkg/MemEncryptSevLib: clean up MemEncryptSevSetPageEncMask() decl Laszlo Ersek
                   ` (18 subsequent siblings)
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:03 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

The declaration and the definition(s) of the function should have
identical leading comments and/or identical parameter lists. Also remove
any excess space in the comment block, and unindent the trailing "**/" if
necessary. Correct several parameter references.

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/Include/Library/MemEncryptSevLib.h                   | 34 +++++++++++---------
 OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c | 34 ++++++++++----------
 OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c  |  7 ++--
 3 files changed, 38 insertions(+), 37 deletions(-)

diff --git a/OvmfPkg/Include/Library/MemEncryptSevLib.h b/OvmfPkg/Include/Library/MemEncryptSevLib.h
index 88b272ebedef..2d574dd30676 100644
--- a/OvmfPkg/Include/Library/MemEncryptSevLib.h
+++ b/OvmfPkg/Include/Library/MemEncryptSevLib.h
@@ -15,63 +15,65 @@
 **/
 
 #ifndef _MEM_ENCRYPT_SEV_LIB_H_
 #define _MEM_ENCRYPT_SEV_LIB_H_
 
 #include <Base.h>
 
 /**
   Returns a boolean to indicate whether SEV is enabled
 
   @retval TRUE           SEV is enabled
   @retval FALSE          SEV is not enabled
 **/
 BOOLEAN
 EFIAPI
 MemEncryptSevIsEnabled (
   VOID
   );
 
 /**
-  This function clears memory encryption bit for the memory region specified
-  by BaseAddress and Number of pages from the current page table context.
+  This function clears memory encryption bit for the memory region specified by
+  BaseAddress and NumPages from the current page table context.
 
-  @param[in]  BaseAddress           The physical address that is the start
-                                    address of a memory region.
-  @param[in]  NumberOfPages         The number of pages from start memory
-                                    region.
-  @param[in]  Flush                 Flush the caches before clearing the bit
-                                    (mostly TRUE except MMIO addresses)
+  @param[in]  Cr3BaseAddress          Cr3 Base Address (if zero then use
+                                      current CR3)
+  @param[in]  BaseAddress             The physical address that is the start
+                                      address of a memory region.
+  @param[in]  NumPages                The number of pages from start memory
+                                      region.
+  @param[in]  Flush                   Flush the caches before clearing the bit
+                                      (mostly TRUE except MMIO addresses)
 
-  @retval RETURN_SUCCESS            The attributes were cleared for the memory
-                                    region.
-  @retval RETURN_INVALID_PARAMETER  Number of pages is zero.
-  @retval RETURN_UNSUPPORTED        Clearing memory encryption attribute is not
-                                    supported
-  **/
+  @retval RETURN_SUCCESS              The attributes were cleared for the
+                                      memory region.
+  @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
+  @retval RETURN_UNSUPPORTED          Clearing the memory encryption attribute
+                                      is not supported
+**/
 RETURN_STATUS
 EFIAPI
 MemEncryptSevClearPageEncMask (
   IN PHYSICAL_ADDRESS         Cr3BaseAddress,
   IN PHYSICAL_ADDRESS         BaseAddress,
-  IN UINTN                    NumberOfPages,
-  IN BOOLEAN                  CacheFlush
+  IN UINTN                    NumPages,
+  IN BOOLEAN                  Flush
   );
 
 /**
   This function sets memory encryption bit for the memory region specified by
   BaseAddress and Number of pages from the current page table context.
 
   @param[in]  BaseAddress           The physical address that is the start
                                     address of a memory region.
   @param[in]  NumberOfPages         The number of pages from start memory
                                     region.
   @param[in]  Flush                 Flush the caches before clearing the bit
                                     (mostly TRUE except MMIO addresses)
 
   @retval RETURN_SUCCESS            The attributes were set for the memory
                                     region.
   @retval RETURN_INVALID_PARAMETER  Number of pages is zero.
   @retval RETURN_UNSUPPORTED        Clearing memory encryption attribute is not
                                     supported
   **/
 RETURN_STATUS
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c b/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c
index d1130df2d0e7..d6067c52aacd 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c
@@ -5,64 +5,64 @@
   Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
 
   This program and the accompanying materials are licensed and made available
   under the terms and conditions of the BSD License which accompanies this
   distribution.  The full text of the license may be found at
   http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
   WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
 **/
 
 #include <Library/BaseLib.h>
 #include <Library/DebugLib.h>
 #include <Register/Cpuid.h>
 #include <Register/Amd/Cpuid.h>
 #include <Register/Amd/Msr.h>
 #include <Library/MemEncryptSevLib.h>
 
 /**
-  This function clears memory encryption bit for the memory region specified
-  by BaseAddress and Number of pages from the current page table context.
+  This function clears memory encryption bit for the memory region specified by
+  BaseAddress and NumPages from the current page table context.
 
-  @param[in]  Cr3BaseAddress        Cr3 Base Address (if zero then use current
-                                    CR3)
-  @param[in]  BaseAddress           The physical address that is the start
-                                    address of a memory region.
-  @param[in]  NumberOfPages         The number of pages from start memory
-                                    region.
-  @param[in]  Flush                 Flush the caches before clearing the bit
-                                    (mostly TRUE except MMIO addresses)
+  @param[in]  Cr3BaseAddress          Cr3 Base Address (if zero then use
+                                      current CR3)
+  @param[in]  BaseAddress             The physical address that is the start
+                                      address of a memory region.
+  @param[in]  NumPages                The number of pages from start memory
+                                      region.
+  @param[in]  Flush                   Flush the caches before clearing the bit
+                                      (mostly TRUE except MMIO addresses)
 
-  @retval RETURN_SUCCESS            The attributes were cleared for the memory
-                                    region.
-  @retval RETURN_INVALID_PARAMETER  Number of pages is zero.
-  @retval RETURN_UNSUPPORTED        Clearing memory encryption attribute is not
-                                    supported
-  **/
+  @retval RETURN_SUCCESS              The attributes were cleared for the
+                                      memory region.
+  @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
+  @retval RETURN_UNSUPPORTED          Clearing the memory encryption attribute
+                                      is not supported
+**/
 RETURN_STATUS
 EFIAPI
 MemEncryptSevClearPageEncMask (
   IN PHYSICAL_ADDRESS         Cr3BaseAddress,
   IN PHYSICAL_ADDRESS         BaseAddress,
-  IN UINTN                    NumberOfPages,
+  IN UINTN                    NumPages,
   IN BOOLEAN                  Flush
   )
 {
   //
   // Memory encryption bit is not accessible in 32-bit mode
   //
   return RETURN_UNSUPPORTED;
 }
 
 /**
   This function sets memory encryption bit for the memory region specified by
   BaseAddress and Number of pages from the current page table context.
 
   @param[in]  Cr3BaseAddress        Cr3 Base Address (if zero then use current
                                     CR3)
   @param[in]  BaseAddress           The physical address that is the start
                                     address of a memory region.
   @param[in]  NumberOfPages         The number of pages from start memory
                                     region.
   @param[in]  Flush                 Flush the caches before clearing the bit
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c
index 4b7fdf7d044d..5b8bc737645c 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c
@@ -7,59 +7,58 @@
   This program and the accompanying materials are licensed and made available
   under the terms and conditions of the BSD License which accompanies this
   distribution.  The full text of the license may be found at
   http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
   WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
 **/
 
 #include <Library/BaseLib.h>
 #include <Library/DebugLib.h>
 #include <Register/Cpuid.h>
 #include <Register/Amd/Cpuid.h>
 #include <Register/Amd/Msr.h>
 #include <Library/MemEncryptSevLib.h>
 
 #include "VirtualMemory.h"
 
 /**
-
   This function clears memory encryption bit for the memory region specified by
-  BaseAddress and Number of pages from the current page table context.
+  BaseAddress and NumPages from the current page table context.
 
   @param[in]  Cr3BaseAddress          Cr3 Base Address (if zero then use
                                       current CR3)
   @param[in]  BaseAddress             The physical address that is the start
                                       address of a memory region.
-  @param[in]  NumberOfPages           The number of pages from start memory
+  @param[in]  NumPages                The number of pages from start memory
                                       region.
   @param[in]  Flush                   Flush the caches before clearing the bit
                                       (mostly TRUE except MMIO addresses)
 
   @retval RETURN_SUCCESS              The attributes were cleared for the
                                       memory region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
   @retval RETURN_UNSUPPORTED          Clearing the memory encryption attribute
                                       is not supported
-  **/
+**/
 RETURN_STATUS
 EFIAPI
 MemEncryptSevClearPageEncMask (
   IN PHYSICAL_ADDRESS         Cr3BaseAddress,
   IN PHYSICAL_ADDRESS         BaseAddress,
   IN UINTN                    NumPages,
   IN BOOLEAN                  Flush
   )
 {
   return InternalMemEncryptSevSetMemoryDecrypted (
            Cr3BaseAddress,
            BaseAddress,
            EFI_PAGES_TO_SIZE (NumPages),
            Flush
            );
 }
 
 /**
 
   This function clears memory encryption bit for the memory region specified by
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 04/20] OvmfPkg/MemEncryptSevLib: clean up MemEncryptSevSetPageEncMask() decl
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (2 preceding siblings ...)
  2018-03-02  0:03 ` [PATCH 03/20] OvmfPkg/MemEncryptSevLib: clean up MemEncryptSevClearPageEncMask() decl Laszlo Ersek
@ 2018-03-02  0:03 ` Laszlo Ersek
  2018-03-02  0:03 ` [PATCH 05/20] OvmfPkg/MemEncryptSevLib: clean up SetMemoryEncDec() comment block Laszlo Ersek
                   ` (17 subsequent siblings)
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:03 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

The declaration and the definition(s) of the function should have
identical leading comments and/or identical parameter lists. Replace any
leftover "clear" references to the C-bit with "set" references. Also
remove any excess space in the comment block, and unindent the trailing
"**/" if necessary. Correct several parameter references.

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/Include/Library/MemEncryptSevLib.h                   | 32 +++++++++++---------
 OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c | 32 ++++++++++----------
 OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c  | 17 +++++------
 3 files changed, 41 insertions(+), 40 deletions(-)

diff --git a/OvmfPkg/Include/Library/MemEncryptSevLib.h b/OvmfPkg/Include/Library/MemEncryptSevLib.h
index 2d574dd30676..e5ebb4401818 100644
--- a/OvmfPkg/Include/Library/MemEncryptSevLib.h
+++ b/OvmfPkg/Include/Library/MemEncryptSevLib.h
@@ -44,44 +44,46 @@ MemEncryptSevIsEnabled (
   @param[in]  Flush                   Flush the caches before clearing the bit
                                       (mostly TRUE except MMIO addresses)
 
   @retval RETURN_SUCCESS              The attributes were cleared for the
                                       memory region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
   @retval RETURN_UNSUPPORTED          Clearing the memory encryption attribute
                                       is not supported
 **/
 RETURN_STATUS
 EFIAPI
 MemEncryptSevClearPageEncMask (
   IN PHYSICAL_ADDRESS         Cr3BaseAddress,
   IN PHYSICAL_ADDRESS         BaseAddress,
   IN UINTN                    NumPages,
   IN BOOLEAN                  Flush
   );
 
 /**
   This function sets memory encryption bit for the memory region specified by
-  BaseAddress and Number of pages from the current page table context.
+  BaseAddress and NumPages from the current page table context.
 
-  @param[in]  BaseAddress           The physical address that is the start
-                                    address of a memory region.
-  @param[in]  NumberOfPages         The number of pages from start memory
-                                    region.
-  @param[in]  Flush                 Flush the caches before clearing the bit
-                                    (mostly TRUE except MMIO addresses)
+  @param[in]  Cr3BaseAddress          Cr3 Base Address (if zero then use
+                                      current CR3)
+  @param[in]  BaseAddress             The physical address that is the start
+                                      address of a memory region.
+  @param[in]  NumPages                The number of pages from start memory
+                                      region.
+  @param[in]  Flush                   Flush the caches before setting the bit
+                                      (mostly TRUE except MMIO addresses)
 
-  @retval RETURN_SUCCESS            The attributes were set for the memory
-                                    region.
-  @retval RETURN_INVALID_PARAMETER  Number of pages is zero.
-  @retval RETURN_UNSUPPORTED        Clearing memory encryption attribute is not
-                                    supported
-  **/
+  @retval RETURN_SUCCESS              The attributes were set for the memory
+                                      region.
+  @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
+  @retval RETURN_UNSUPPORTED          Setting the memory encryption attribute
+                                      is not supported
+**/
 RETURN_STATUS
 EFIAPI
 MemEncryptSevSetPageEncMask (
   IN PHYSICAL_ADDRESS         Cr3BaseAddress,
   IN PHYSICAL_ADDRESS         BaseAddress,
-  IN UINTN                    NumberOfPages,
-  IN BOOLEAN                  CacheFlush
+  IN UINTN                    NumPages,
+  IN BOOLEAN                  Flush
   );
 #endif // _MEM_ENCRYPT_SEV_LIB_H_
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c b/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c
index d6067c52aacd..614c97b23bb6 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c
@@ -40,51 +40,51 @@
   @retval RETURN_UNSUPPORTED          Clearing the memory encryption attribute
                                       is not supported
 **/
 RETURN_STATUS
 EFIAPI
 MemEncryptSevClearPageEncMask (
   IN PHYSICAL_ADDRESS         Cr3BaseAddress,
   IN PHYSICAL_ADDRESS         BaseAddress,
   IN UINTN                    NumPages,
   IN BOOLEAN                  Flush
   )
 {
   //
   // Memory encryption bit is not accessible in 32-bit mode
   //
   return RETURN_UNSUPPORTED;
 }
 
 /**
   This function sets memory encryption bit for the memory region specified by
-  BaseAddress and Number of pages from the current page table context.
+  BaseAddress and NumPages from the current page table context.
 
-  @param[in]  Cr3BaseAddress        Cr3 Base Address (if zero then use current
-                                    CR3)
-  @param[in]  BaseAddress           The physical address that is the start
-                                    address of a memory region.
-  @param[in]  NumberOfPages         The number of pages from start memory
-                                    region.
-  @param[in]  Flush                 Flush the caches before clearing the bit
-                                    (mostly TRUE except MMIO addresses)
+  @param[in]  Cr3BaseAddress          Cr3 Base Address (if zero then use
+                                      current CR3)
+  @param[in]  BaseAddress             The physical address that is the start
+                                      address of a memory region.
+  @param[in]  NumPages                The number of pages from start memory
+                                      region.
+  @param[in]  Flush                   Flush the caches before setting the bit
+                                      (mostly TRUE except MMIO addresses)
 
-  @retval RETURN_SUCCESS            The attributes were set for the memory
-                                    region.
-  @retval RETURN_INVALID_PARAMETER  Number of pages is zero.
-  @retval RETURN_UNSUPPORTED        Clearing memory encryption attribute is not
-                                    supported
-  **/
+  @retval RETURN_SUCCESS              The attributes were set for the memory
+                                      region.
+  @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
+  @retval RETURN_UNSUPPORTED          Setting the memory encryption attribute
+                                      is not supported
+**/
 RETURN_STATUS
 EFIAPI
 MemEncryptSevSetPageEncMask (
   IN PHYSICAL_ADDRESS         Cr3BaseAddress,
   IN PHYSICAL_ADDRESS         BaseAddress,
-  IN UINTN                    NumberOfPages,
+  IN UINTN                    NumPages,
   IN BOOLEAN                  Flush
   )
 {
   //
   // Memory encryption bit is not accessible in 32-bit mode
   //
   return RETURN_UNSUPPORTED;
 }
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c
index 5b8bc737645c..f165722ae550 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c
@@ -43,55 +43,54 @@
                                       is not supported
 **/
 RETURN_STATUS
 EFIAPI
 MemEncryptSevClearPageEncMask (
   IN PHYSICAL_ADDRESS         Cr3BaseAddress,
   IN PHYSICAL_ADDRESS         BaseAddress,
   IN UINTN                    NumPages,
   IN BOOLEAN                  Flush
   )
 {
   return InternalMemEncryptSevSetMemoryDecrypted (
            Cr3BaseAddress,
            BaseAddress,
            EFI_PAGES_TO_SIZE (NumPages),
            Flush
            );
 }
 
 /**
-
-  This function clears memory encryption bit for the memory region specified by
-  BaseAddress and Number of pages from the current page table context.
+  This function sets memory encryption bit for the memory region specified by
+  BaseAddress and NumPages from the current page table context.
 
   @param[in]  Cr3BaseAddress          Cr3 Base Address (if zero then use
                                       current CR3)
   @param[in]  BaseAddress             The physical address that is the start
                                       address of a memory region.
-  @param[in]  NumberOfPages           The number of pages from start memory
+  @param[in]  NumPages                The number of pages from start memory
                                       region.
-  @param[in]  Flush                   Flush the caches before clearing the bit
+  @param[in]  Flush                   Flush the caches before setting the bit
                                       (mostly TRUE except MMIO addresses)
 
-  @retval RETURN_SUCCESS              The attributes were cleared for the
-                                      memory region.
+  @retval RETURN_SUCCESS              The attributes were set for the memory
+                                      region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
-  @retval RETURN_UNSUPPORTED          Clearing the memory encryption attribute
+  @retval RETURN_UNSUPPORTED          Setting the memory encryption attribute
                                       is not supported
-  **/
+**/
 RETURN_STATUS
 EFIAPI
 MemEncryptSevSetPageEncMask (
   IN PHYSICAL_ADDRESS         Cr3BaseAddress,
   IN PHYSICAL_ADDRESS         BaseAddress,
   IN UINTN                    NumPages,
   IN BOOLEAN                  Flush
   )
 {
   return InternalMemEncryptSevSetMemoryEncrypted (
            Cr3BaseAddress,
            BaseAddress,
            EFI_PAGES_TO_SIZE (NumPages),
            Flush
            );
 }
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 05/20] OvmfPkg/MemEncryptSevLib: clean up SetMemoryEncDec() comment block
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (3 preceding siblings ...)
  2018-03-02  0:03 ` [PATCH 04/20] OvmfPkg/MemEncryptSevLib: clean up MemEncryptSevSetPageEncMask() decl Laszlo Ersek
@ 2018-03-02  0:03 ` Laszlo Ersek
  2018-03-02  0:03 ` [PATCH 06/20] OvmfPkg/MemEncryptSevLib: clean up InternalMemEncryptSevSetMemoryDecrypted() decl Laszlo Ersek
                   ` (16 subsequent siblings)
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:03 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

Document the "Cr3BaseAddress" parameter, and correct several parameter
references.

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
index 65b8babaac44..aed92127629f 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
@@ -531,55 +531,57 @@ DisableReadOnlyPageWriteProtect (
   VOID
   )
 {
   AsmWriteCr0 (AsmReadCr0() & ~BIT16);
 }
 
 /**
  Enable Write Protect on pages marked as read-only.
 **/
 VOID
 EnableReadOnlyPageWriteProtect (
   VOID
   )
 {
   AsmWriteCr0 (AsmReadCr0() | BIT16);
 }
 
 
 /**
   This function either sets or clears memory encryption bit for the memory
-  region specified by PhysicalAddress and length from the current page table
+  region specified by PhysicalAddress and Length from the current page table
   context.
 
-  The function iterates through the physicalAddress one page at a time, and set
+  The function iterates through the PhysicalAddress one page at a time, and set
   or clears the memory encryption mask in the page table. If it encounters
   that a given physical address range is part of large page then it attempts to
   change the attribute at one go (based on size), otherwise it splits the
   large pages into smaller (e.g 2M page into 4K pages) and then try to set or
   clear the encryption bit on the smallest page size.
 
+  @param[in]  Cr3BaseAddress          Cr3 Base Address (if zero then use
+                                      current CR3)
   @param[in]  PhysicalAddress         The physical address that is the start
                                       address of a memory region.
   @param[in]  Length                  The length of memory region
   @param[in]  Mode                    Set or Clear mode
-  @param[in]  Flush                   Flush the caches before applying the
+  @param[in]  CacheFlush              Flush the caches before applying the
                                       encryption mask
 
   @retval RETURN_SUCCESS              The attributes were cleared for the
                                       memory region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
   @retval RETURN_UNSUPPORTED          Setting the memory encyrption attribute
                                       is not supported
 **/
 
 STATIC
 RETURN_STATUS
 EFIAPI
 SetMemoryEncDec (
   IN    PHYSICAL_ADDRESS         Cr3BaseAddress,
   IN    PHYSICAL_ADDRESS         PhysicalAddress,
   IN    UINTN                    Length,
   IN    MAP_RANGE_MODE           Mode,
   IN    BOOLEAN                  CacheFlush
   )
 {
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 06/20] OvmfPkg/MemEncryptSevLib: clean up InternalMemEncryptSevSetMemoryDecrypted() decl
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (4 preceding siblings ...)
  2018-03-02  0:03 ` [PATCH 05/20] OvmfPkg/MemEncryptSevLib: clean up SetMemoryEncDec() comment block Laszlo Ersek
@ 2018-03-02  0:03 ` Laszlo Ersek
  2018-03-02  0:03 ` [PATCH 07/20] OvmfPkg/MemEncryptSevLib: clean up InternalMemEncryptSevSetMemoryEncrypted() decl Laszlo Ersek
                   ` (15 subsequent siblings)
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:03 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

The declaration and the definition(s) of the function should have
identical leading comments and/or identical parameter lists. Document the
"Cr3BaseAddress" parameter, and correct several parameter references.
Replace a "set" reference to the C-bit with a "clear" reference.

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h | 14 ++++++++------
 OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c |  6 ++++--
 2 files changed, 12 insertions(+), 8 deletions(-)

diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h
index 7dd1bbe0eb26..646a9781d04a 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h
@@ -171,61 +171,63 @@ typedef union {
 #define PTE_OFFSET(x)               ( (x >> 12) & PAGETABLE_ENTRY_MASK)
 #define PAGING_1G_ADDRESS_MASK_64   0x000FFFFFC0000000ull
 
 #define PAGE_TABLE_POOL_ALIGNMENT   BASE_2MB
 #define PAGE_TABLE_POOL_UNIT_SIZE   SIZE_2MB
 #define PAGE_TABLE_POOL_UNIT_PAGES  \
   EFI_SIZE_TO_PAGES (PAGE_TABLE_POOL_UNIT_SIZE)
 #define PAGE_TABLE_POOL_ALIGN_MASK  \
   (~(EFI_PHYSICAL_ADDRESS)(PAGE_TABLE_POOL_ALIGNMENT - 1))
 
 typedef struct {
   VOID            *NextPool;
   UINTN           Offset;
   UINTN           FreePages;
 } PAGE_TABLE_POOL;
 
 
 
 /**
   This function clears memory encryption bit for the memory region specified by
-  PhysicalAddress and length from the current page table context.
+  PhysicalAddress and Length from the current page table context.
 
+  @param[in]  Cr3BaseAddress          Cr3 Base Address (if zero then use
+                                      current CR3)
   @param[in]  PhysicalAddress         The physical address that is the start
                                       address of a memory region.
   @param[in]  Length                  The length of memory region
   @param[in]  Flush                   Flush the caches before applying the
                                       encryption mask
 
   @retval RETURN_SUCCESS              The attributes were cleared for the
                                       memory region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
-  @retval RETURN_UNSUPPORTED          Setting the memory encyrption attribute
+  @retval RETURN_UNSUPPORTED          Clearing the memory encyrption attribute
                                       is not supported
 **/
 RETURN_STATUS
 EFIAPI
 InternalMemEncryptSevSetMemoryDecrypted (
-  IN  PHYSICAL_ADDRESS     Cr3BaseAddress,
-  IN  PHYSICAL_ADDRESS     PhysicalAddress,
-  IN  UINT64               Length,
-  IN  BOOLEAN              CacheFlush
+  IN  PHYSICAL_ADDRESS        Cr3BaseAddress,
+  IN  PHYSICAL_ADDRESS        PhysicalAddress,
+  IN  UINTN                   Length,
+  IN  BOOLEAN                 Flush
   );
 
 /**
   This function sets memory encryption bit for the memory region specified by
   PhysicalAddress and length from the current page table context.
 
   @param[in]  PhysicalAddress         The physical address that is the start
                                       address of a memory region.
   @param[in]  Length                  The length of memory region
   @param[in]  Flush                   Flush the caches before applying the
                                       encryption mask
 
   @retval RETURN_SUCCESS              The attributes were cleared for the
                                       memory region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
   @retval RETURN_UNSUPPORTED          Setting the memory encyrption attribute
                                       is not supported
 **/
 RETURN_STATUS
 EFIAPI
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
index aed92127629f..3f7704801c9c 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
@@ -809,52 +809,54 @@ SetMemoryEncDec (
   }
 
   //
   // Flush TLB
   //
   CpuFlushTlb();
 
 Done:
   //
   // Restore page table write protection, if any.
   //
   if (IsWpEnabled) {
     EnableReadOnlyPageWriteProtect ();
   }
 
   return Status;
 }
 
 /**
   This function clears memory encryption bit for the memory region specified by
-  PhysicalAddress and length from the current page table context.
+  PhysicalAddress and Length from the current page table context.
 
+  @param[in]  Cr3BaseAddress          Cr3 Base Address (if zero then use
+                                      current CR3)
   @param[in]  PhysicalAddress         The physical address that is the start
                                       address of a memory region.
   @param[in]  Length                  The length of memory region
   @param[in]  Flush                   Flush the caches before applying the
                                       encryption mask
 
   @retval RETURN_SUCCESS              The attributes were cleared for the
                                       memory region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
-  @retval RETURN_UNSUPPORTED          Setting the memory encyrption attribute
+  @retval RETURN_UNSUPPORTED          Clearing the memory encyrption attribute
                                       is not supported
 **/
 RETURN_STATUS
 EFIAPI
 InternalMemEncryptSevSetMemoryDecrypted (
   IN  PHYSICAL_ADDRESS        Cr3BaseAddress,
   IN  PHYSICAL_ADDRESS        PhysicalAddress,
   IN  UINTN                   Length,
   IN  BOOLEAN                 Flush
   )
 {
 
   return SetMemoryEncDec (
            Cr3BaseAddress,
            PhysicalAddress,
            Length,
            ClearCBit,
            Flush
            );
 }
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 07/20] OvmfPkg/MemEncryptSevLib: clean up InternalMemEncryptSevSetMemoryEncrypted() decl
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (5 preceding siblings ...)
  2018-03-02  0:03 ` [PATCH 06/20] OvmfPkg/MemEncryptSevLib: clean up InternalMemEncryptSevSetMemoryDecrypted() decl Laszlo Ersek
@ 2018-03-02  0:03 ` Laszlo Ersek
  2018-03-02  0:03 ` [PATCH 08/20] OvmfPkg/MemEncryptSevLib: sort #includes, and entries in INF file sections Laszlo Ersek
                   ` (14 subsequent siblings)
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:03 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

The declaration and the definition(s) of the function should have
identical leading comments and/or identical parameter lists. Document the
"Cr3BaseAddress" parameter, and correct several parameter references.
Replace a "clear" reference to the C-bit with a "set" reference.

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h | 16 +++++++++-------
 OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c |  8 +++++---
 2 files changed, 14 insertions(+), 10 deletions(-)

diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h
index 646a9781d04a..67ff69122d73 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h
@@ -198,44 +198,46 @@ typedef struct {
   @param[in]  Flush                   Flush the caches before applying the
                                       encryption mask
 
   @retval RETURN_SUCCESS              The attributes were cleared for the
                                       memory region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
   @retval RETURN_UNSUPPORTED          Clearing the memory encyrption attribute
                                       is not supported
 **/
 RETURN_STATUS
 EFIAPI
 InternalMemEncryptSevSetMemoryDecrypted (
   IN  PHYSICAL_ADDRESS        Cr3BaseAddress,
   IN  PHYSICAL_ADDRESS        PhysicalAddress,
   IN  UINTN                   Length,
   IN  BOOLEAN                 Flush
   );
 
 /**
   This function sets memory encryption bit for the memory region specified by
-  PhysicalAddress and length from the current page table context.
+  PhysicalAddress and Length from the current page table context.
 
+  @param[in]  Cr3BaseAddress          Cr3 Base Address (if zero then use
+                                      current CR3)
   @param[in]  PhysicalAddress         The physical address that is the start
                                       address of a memory region.
   @param[in]  Length                  The length of memory region
   @param[in]  Flush                   Flush the caches before applying the
                                       encryption mask
 
-  @retval RETURN_SUCCESS              The attributes were cleared for the
-                                      memory region.
+  @retval RETURN_SUCCESS              The attributes were set for the memory
+                                      region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
   @retval RETURN_UNSUPPORTED          Setting the memory encyrption attribute
                                       is not supported
 **/
 RETURN_STATUS
 EFIAPI
 InternalMemEncryptSevSetMemoryEncrypted (
-  IN  PHYSICAL_ADDRESS     Cr3BaseAddress,
-  IN  PHYSICAL_ADDRESS     PhysicalAddress,
-  IN  UINT64               Length,
-  IN  BOOLEAN              CacheFlush
+  IN  PHYSICAL_ADDRESS        Cr3BaseAddress,
+  IN  PHYSICAL_ADDRESS        PhysicalAddress,
+  IN  UINTN                   Length,
+  IN  BOOLEAN                 Flush
   );
 
 #endif
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
index 3f7704801c9c..39b246048f1f 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
@@ -846,50 +846,52 @@ RETURN_STATUS
 EFIAPI
 InternalMemEncryptSevSetMemoryDecrypted (
   IN  PHYSICAL_ADDRESS        Cr3BaseAddress,
   IN  PHYSICAL_ADDRESS        PhysicalAddress,
   IN  UINTN                   Length,
   IN  BOOLEAN                 Flush
   )
 {
 
   return SetMemoryEncDec (
            Cr3BaseAddress,
            PhysicalAddress,
            Length,
            ClearCBit,
            Flush
            );
 }
 
 /**
   This function sets memory encryption bit for the memory region specified by
-  PhysicalAddress and length from the current page table context.
+  PhysicalAddress and Length from the current page table context.
 
+  @param[in]  Cr3BaseAddress          Cr3 Base Address (if zero then use
+                                      current CR3)
   @param[in]  PhysicalAddress         The physical address that is the start
                                       address of a memory region.
   @param[in]  Length                  The length of memory region
   @param[in]  Flush                   Flush the caches before applying the
                                       encryption mask
 
-  @retval RETURN_SUCCESS              The attributes were cleared for the
-                                      memory region.
+  @retval RETURN_SUCCESS              The attributes were set for the memory
+                                      region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
   @retval RETURN_UNSUPPORTED          Setting the memory encyrption attribute
                                       is not supported
 **/
 RETURN_STATUS
 EFIAPI
 InternalMemEncryptSevSetMemoryEncrypted (
   IN  PHYSICAL_ADDRESS        Cr3BaseAddress,
   IN  PHYSICAL_ADDRESS        PhysicalAddress,
   IN  UINTN                   Length,
   IN  BOOLEAN                 Flush
   )
 {
   return SetMemoryEncDec (
            Cr3BaseAddress,
            PhysicalAddress,
            Length,
            SetCBit,
            Flush
            );
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 08/20] OvmfPkg/MemEncryptSevLib: sort #includes, and entries in INF file sections
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (6 preceding siblings ...)
  2018-03-02  0:03 ` [PATCH 07/20] OvmfPkg/MemEncryptSevLib: clean up InternalMemEncryptSevSetMemoryEncrypted() decl Laszlo Ersek
@ 2018-03-02  0:03 ` Laszlo Ersek
  2018-03-02  0:03 ` [PATCH 09/20] OvmfPkg/PlatformPei: sort #includes in "AmdSev.c" Laszlo Ersek
                   ` (13 subsequent siblings)
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:03 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf   | 6 +++---
 OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h        | 4 ++--
 OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c    | 4 ++--
 OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c | 4 ++--
 OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c     | 4 ++--
 OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c        | 2 +-
 6 files changed, 12 insertions(+), 12 deletions(-)

diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf b/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
index 81b075194ace..2f0a2392a7ad 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
@@ -14,40 +14,40 @@
 #
 #
 ##
 
 [Defines]
   INF_VERSION                    = 1.25
   BASE_NAME                      = MemEncryptSevLib
   FILE_GUID                      = c1594631-3888-4be4-949f-9c630dbc842b
   MODULE_TYPE                    = BASE
   VERSION_STRING                 = 1.0
   LIBRARY_CLASS                  = MemEncryptSevLib|PEIM DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER UEFI_DRIVER
 
 #
 # The following information is for reference only and not required by the build
 # tools.
 #
 # VALID_ARCHITECTURES           = IA32 X64
 #
 
 [Packages]
-  MdePkg/MdePkg.dec
   MdeModulePkg/MdeModulePkg.dec
+  MdePkg/MdePkg.dec
   OvmfPkg/OvmfPkg.dec
   UefiCpuPkg/UefiCpuPkg.dec
 
 [Sources.X64]
   MemEncryptSevLibInternal.c
   X64/MemEncryptSevLib.c
   X64/VirtualMemory.c
 
 [Sources.IA32]
-  MemEncryptSevLibInternal.c
   Ia32/MemEncryptSevLib.c
+  MemEncryptSevLibInternal.c
 
 [LibraryClasses]
   BaseLib
-  CpuLib
   CacheMaintenanceLib
+  CpuLib
   DebugLib
   MemoryAllocationLib
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h
index 67ff69122d73..95a08f3558e9 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h
@@ -3,47 +3,47 @@
   Virtual Memory Management Services to set or clear the memory encryption bit
 
   Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>
   Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
 
   This program and the accompanying materials are licensed and made available
   under the terms and conditions of the BSD License which accompanies this
   distribution.  The full text of the license may be found at
   http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT
   WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
   Code is derived from MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.h
 
 **/
 
 #ifndef __VIRTUAL_MEMORY__
 #define __VIRTUAL_MEMORY__
 
-#include <Uefi.h>
 #include <Library/BaseLib.h>
 #include <Library/BaseMemoryLib.h>
+#include <Library/CacheMaintenanceLib.h>
 #include <Library/DebugLib.h>
 #include <Library/MemoryAllocationLib.h>
+#include <Uefi.h>
 
-#include <Library/CacheMaintenanceLib.h>
 #define SYS_CODE64_SEL 0x38
 
 #pragma pack(1)
 
 //
 // Page-Map Level-4 Offset (PML4) and
 // Page-Directory-Pointer Offset (PDPE) entries 4K & 2MB
 //
 
 typedef union {
   struct {
     UINT64  Present:1;                // 0 = Not present in memory,
                                       //   1 = Present in memory
     UINT64  ReadWrite:1;              // 0 = Read-Only, 1= Read/Write
     UINT64  UserSupervisor:1;         // 0 = Supervisor, 1=User
     UINT64  WriteThrough:1;           // 0 = Write-Back caching,
                                       //   1 = Write-Through caching
     UINT64  CacheDisabled:1;          // 0 = Cached, 1=Non-Cached
     UINT64  Accessed:1;               // 0 = Not accessed,
                                       //   1 = Accessed (set by CPU)
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c b/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c
index 614c97b23bb6..5d909c17b0bc 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c
@@ -1,42 +1,42 @@
 /** @file
 
   Secure Encrypted Virtualization (SEV) library helper function
 
   Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
 
   This program and the accompanying materials are licensed and made available
   under the terms and conditions of the BSD License which accompanies this
   distribution.  The full text of the license may be found at
   http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
   WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
 **/
 
 #include <Library/BaseLib.h>
 #include <Library/DebugLib.h>
-#include <Register/Cpuid.h>
+#include <Library/MemEncryptSevLib.h>
 #include <Register/Amd/Cpuid.h>
 #include <Register/Amd/Msr.h>
-#include <Library/MemEncryptSevLib.h>
+#include <Register/Cpuid.h>
 
 /**
   This function clears memory encryption bit for the memory region specified by
   BaseAddress and NumPages from the current page table context.
 
   @param[in]  Cr3BaseAddress          Cr3 Base Address (if zero then use
                                       current CR3)
   @param[in]  BaseAddress             The physical address that is the start
                                       address of a memory region.
   @param[in]  NumPages                The number of pages from start memory
                                       region.
   @param[in]  Flush                   Flush the caches before clearing the bit
                                       (mostly TRUE except MMIO addresses)
 
   @retval RETURN_SUCCESS              The attributes were cleared for the
                                       memory region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
   @retval RETURN_UNSUPPORTED          Clearing the memory encryption attribute
                                       is not supported
 **/
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c b/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c
index 44c2c98a6afc..7078ab0d3f46 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c
@@ -1,42 +1,42 @@
 /** @file
 
   Secure Encrypted Virtualization (SEV) library helper function
 
   Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
 
   This program and the accompanying materials are licensed and made available
   under the terms and conditions of the BSD License which accompanies this
   distribution.  The full text of the license may be found at
   http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
   WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
 **/
 
 #include <Library/BaseLib.h>
 #include <Library/DebugLib.h>
-#include <Register/Cpuid.h>
+#include <Library/MemEncryptSevLib.h>
 #include <Register/Amd/Cpuid.h>
 #include <Register/Amd/Msr.h>
-#include <Library/MemEncryptSevLib.h>
+#include <Register/Cpuid.h>
 
 STATIC BOOLEAN mSevStatus = FALSE;
 STATIC BOOLEAN mSevStatusChecked = FALSE;
 
 /**
 
   Returns a boolean to indicate whether SEV is enabled
 
   @retval TRUE           SEV is enabled
   @retval FALSE          SEV is not enabled
   **/
 STATIC
 BOOLEAN
 EFIAPI
 InternalMemEncryptSevIsEnabled (
   VOID
   )
 {
   UINT32                            RegEax;
   MSR_SEV_STATUS_REGISTER           Msr;
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c
index f165722ae550..62059242fc79 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c
@@ -1,42 +1,42 @@
 /** @file
 
   Secure Encrypted Virtualization (SEV) library helper function
 
   Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
 
   This program and the accompanying materials are licensed and made available
   under the terms and conditions of the BSD License which accompanies this
   distribution.  The full text of the license may be found at
   http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
   WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
 **/
 
 #include <Library/BaseLib.h>
 #include <Library/DebugLib.h>
-#include <Register/Cpuid.h>
+#include <Library/MemEncryptSevLib.h>
 #include <Register/Amd/Cpuid.h>
 #include <Register/Amd/Msr.h>
-#include <Library/MemEncryptSevLib.h>
+#include <Register/Cpuid.h>
 
 #include "VirtualMemory.h"
 
 /**
   This function clears memory encryption bit for the memory region specified by
   BaseAddress and NumPages from the current page table context.
 
   @param[in]  Cr3BaseAddress          Cr3 Base Address (if zero then use
                                       current CR3)
   @param[in]  BaseAddress             The physical address that is the start
                                       address of a memory region.
   @param[in]  NumPages                The number of pages from start memory
                                       region.
   @param[in]  Flush                   Flush the caches before clearing the bit
                                       (mostly TRUE except MMIO addresses)
 
   @retval RETURN_SUCCESS              The attributes were cleared for the
                                       memory region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
   @retval RETURN_UNSUPPORTED          Clearing the memory encryption attribute
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
index 39b246048f1f..c1bfa35d7a30 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
@@ -1,42 +1,42 @@
 /** @file
 
   Virtual Memory Management Services to set or clear the memory encryption bit
 
   Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>
   Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
 
   This program and the accompanying materials are licensed and made available
   under the terms and conditions of the BSD License which accompanies this
   distribution.  The full text of the license may be found at
   http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT
   WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
   Code is derived from MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c
 
 **/
 
 #include <Library/CpuLib.h>
-#include <Register/Cpuid.h>
 #include <Register/Amd/Cpuid.h>
+#include <Register/Cpuid.h>
 
 #include "VirtualMemory.h"
 
 STATIC BOOLEAN mAddressEncMaskChecked = FALSE;
 STATIC UINT64  mAddressEncMask;
 STATIC PAGE_TABLE_POOL   *mPageTablePool = NULL;
 
 typedef enum {
    SetCBit,
    ClearCBit
 } MAP_RANGE_MODE;
 
 /**
   Get the memory encryption mask
 
   @param[out]      EncryptionMask        contains the pte mask.
 
 **/
 STATIC
 UINT64
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 09/20] OvmfPkg/PlatformPei: sort #includes in "AmdSev.c"
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (7 preceding siblings ...)
  2018-03-02  0:03 ` [PATCH 08/20] OvmfPkg/MemEncryptSevLib: sort #includes, and entries in INF file sections Laszlo Ersek
@ 2018-03-02  0:03 ` Laszlo Ersek
  2018-03-02  0:03 ` [PATCH 10/20] OvmfPkg/SmmCpuFeaturesLib: rewrap to 79 columns Laszlo Ersek
                   ` (12 subsequent siblings)
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:03 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

No functional changes.

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/PlatformPei/AmdSev.c | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)

diff --git a/OvmfPkg/PlatformPei/AmdSev.c b/OvmfPkg/PlatformPei/AmdSev.c
index ad31b69fb032..1509f260fb0b 100644
--- a/OvmfPkg/PlatformPei/AmdSev.c
+++ b/OvmfPkg/PlatformPei/AmdSev.c
@@ -1,44 +1,43 @@
 /**@file
   Initialize Secure Encrypted Virtualization (SEV) support
 
   Copyright (c) 2017, Advanced Micro Devices. All rights reserved.<BR>
 
   This program and the accompanying materials
   are licensed and made available under the terms and conditions of the BSD
   License which accompanies this distribution.  The full text of the license
   may be found at http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
   WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
 **/
 //
 // The package level header files this module uses
 //
-#include <PiPei.h>
-
 #include <Library/DebugLib.h>
+#include <Library/MemEncryptSevLib.h>
 #include <Library/PcdLib.h>
-#include <Register/Cpuid.h>
+#include <PiPei.h>
 #include <Register/Amd/Cpuid.h>
-#include <Library/MemEncryptSevLib.h>
+#include <Register/Cpuid.h>
 
 #include "Platform.h"
 
 /**
 
   Function checks if SEV support is available, if present then it sets
   the dynamic PcdPteMemoryEncryptionAddressOrMask with memory encryption mask.
 
   **/
 VOID
 AmdSevInitialize (
   VOID
   )
 {
   CPUID_MEMORY_ENCRYPTION_INFO_EBX  Ebx;
   UINT64                            EncryptionMask;
   RETURN_STATUS                     PcdStatus;
 
   //
   // Check if SEV is enabled
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 10/20] OvmfPkg/SmmCpuFeaturesLib: rewrap to 79 columns
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (8 preceding siblings ...)
  2018-03-02  0:03 ` [PATCH 09/20] OvmfPkg/PlatformPei: sort #includes in "AmdSev.c" Laszlo Ersek
@ 2018-03-02  0:03 ` Laszlo Ersek
  2018-03-02  0:03 ` [PATCH 11/20] OvmfPkg/SmmCpuFeaturesLib: upper-case the "static" keyword Laszlo Ersek
                   ` (11 subsequent siblings)
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:03 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

There are many overlong lines; it's hard to work with the library like
this. Rewrap all files to 79 columns.

(

The rewrapping of the "mSmmCpuRegisterRanges" and "mSmmCpuWidthOffset"
arrays was verified by hexdumping the arrays in
SmmCpuFeaturesLibConstructor(), both before and after the patch, and
comparing the dumps.

Contents of "mSmmCpuRegisterRanges", IA32 build:

> mSmmCpuRegisterRanges: {
> mSmmCpuRegisterRanges: 000000 04 00 00 00 0A 00 00 00 07 00 00 00 14 00 00 00
> mSmmCpuRegisterRanges: 000010 2E 00 00 00 1B 00 00 00 33 00 00 00 36 00 00 00
> mSmmCpuRegisterRanges: 000020 04 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
> mSmmCpuRegisterRanges: }

Contents of "mSmmCpuRegisterRanges", X64 build:

> mSmmCpuRegisterRanges: {
> mSmmCpuRegisterRanges: 000000 04 00 00 00 0A 00 00 00 07 00 00 00 00 00 00 00
> mSmmCpuRegisterRanges: 000010 14 00 00 00 2E 00 00 00 1B 00 00 00 00 00 00 00
> mSmmCpuRegisterRanges: 000020 33 00 00 00 36 00 00 00 04 00 00 00 00 00 00 00
> mSmmCpuRegisterRanges: 000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
> mSmmCpuRegisterRanges: }

Contents of "mSmmCpuWidthOffset", both IA32 and X64 builds:

> mSmmCpuWidthOffset: {
> mSmmCpuWidthOffset: 000000 00 00 00 00 00 00 00 00 00 00 00 08 00 00 68 02
> mSmmCpuWidthOffset: 000010 6C 02 00 00 00 08 00 00 88 02 8C 02 00 00 00 08
> mSmmCpuWidthOffset: 000020 00 00 78 02 7C 02 00 00 00 00 00 00 64 02 68 02
> mSmmCpuWidthOffset: 000030 00 00 00 00 00 00 84 02 88 02 00 00 00 00 00 00
> mSmmCpuWidthOffset: 000040 74 02 78 02 00 00 00 00 00 00 00 00 04 00 00 00
> mSmmCpuWidthOffset: 000050 04 04 A8 03 00 02 00 00 00 00 04 04 AC 03 10 02
> mSmmCpuWidthOffset: 000060 00 00 00 00 04 04 B0 03 20 02 00 00 00 00 04 04
> mSmmCpuWidthOffset: 000070 B4 03 30 02 00 00 00 00 04 04 B8 03 40 02 00 00
> mSmmCpuWidthOffset: 000080 00 00 04 04 BC 03 50 02 00 00 00 00 00 04 00 00
> mSmmCpuWidthOffset: 000090 70 02 00 00 00 00 04 04 C4 03 90 02 00 00 00 00
> mSmmCpuWidthOffset: 0000A0 04 08 C8 03 60 03 64 03 00 00 04 08 CC 03 68 03
> mSmmCpuWidthOffset: 0000B0 6C 03 00 00 00 08 00 00 B8 03 BC 03 01 00 00 08
> mSmmCpuWidthOffset: 0000C0 00 00 B0 03 B4 03 01 00 00 08 00 00 A8 03 AC 03
> mSmmCpuWidthOffset: 0000D0 01 00 00 08 00 00 A0 03 A4 03 01 00 00 08 00 00
> mSmmCpuWidthOffset: 0000E0 98 03 9C 03 01 00 00 08 00 00 90 03 94 03 01 00
> mSmmCpuWidthOffset: 0000F0 00 08 00 00 88 03 8C 03 01 00 00 08 00 00 80 03
> mSmmCpuWidthOffset: 000100 84 03 01 00 04 08 D0 03 F8 03 FC 03 01 00 04 08
> mSmmCpuWidthOffset: 000110 DC 03 E0 03 E4 03 01 00 04 08 D4 03 F0 03 F4 03
> mSmmCpuWidthOffset: 000120 01 00 04 08 D8 03 E8 03 EC 03 01 00 04 08 E0 03
> mSmmCpuWidthOffset: 000130 D8 03 DC 03 01 00 04 08 E4 03 D0 03 D4 03 01 00
> mSmmCpuWidthOffset: 000140 04 08 E8 03 C8 03 CC 03 01 00 04 08 EC 03 C0 03
> mSmmCpuWidthOffset: 000150 C4 03 01 00 04 08 F0 03 78 03 7C 03 01 00 04 08
> mSmmCpuWidthOffset: 000160 F4 03 70 03 74 03 01 00 04 08 FC 03 58 03 5C 03
> mSmmCpuWidthOffset: 000170 00 00 04 08 F8 03 50 03 54 03 00 00 00 04 00 00
> mSmmCpuWidthOffset: 000180 48 03 4C 03 00 00
> mSmmCpuWidthOffset: }

)

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf |  10 +-
 OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c   | 594 ++++++++++++++++----
 2 files changed, 489 insertions(+), 115 deletions(-)

diff --git a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
index 31edf3a9c1fd..75b24606b9df 100644
--- a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
+++ b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
@@ -1,31 +1,33 @@
 ## @file
 #  The CPU specific programming for PiSmmCpuDxeSmm module.
 #
 #  Copyright (c) 2009 - 2015, Intel Corporation. All rights reserved.<BR>
-#  This program and the accompanying materials
-#  are licensed and made available under the terms and conditions of the BSD License
-#  which accompanies this distribution.  The full text of the license may be found at
+#
+#  This program and the accompanying materials are licensed and made available
+#  under the terms and conditions of the BSD License which accompanies this
+#  distribution.  The full text of the license may be found at
 #  http://opensource.org/licenses/bsd-license.php
 #
 #  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-#  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR
+#  IMPLIED.
 #
 ##
 
 [Defines]
   INF_VERSION                    = 0x00010005
   BASE_NAME                      = SmmCpuFeaturesLib
   MODULE_UNI_FILE                = SmmCpuFeaturesLib.uni
   FILE_GUID                      = AC9991BE-D77A-464C-A8DE-A873DB8A4836
   MODULE_TYPE                    = DXE_SMM_DRIVER
   VERSION_STRING                 = 1.0
   LIBRARY_CLASS                  = SmmCpuFeaturesLib
   CONSTRUCTOR                    = SmmCpuFeaturesLibConstructor
 
 [Sources]
   SmmCpuFeaturesLib.c
 
 [Packages]
   MdePkg/MdePkg.dec
   OvmfPkg/OvmfPkg.dec
   UefiCpuPkg/UefiCpuPkg.dec
diff --git a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
index a307f64c9c61..a876a6e34751 100644
--- a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
+++ b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
@@ -1,32 +1,32 @@
 /** @file
-The CPU specific programming for PiSmmCpuDxeSmm module.
+  The CPU specific programming for PiSmmCpuDxeSmm module.
 
-Copyright (c) 2010 - 2015, Intel Corporation. All rights reserved.<BR>
-This program and the accompanying materials
-are licensed and made available under the terms and conditions of the BSD License
-which accompanies this distribution.  The full text of the license may be found at
-http://opensource.org/licenses/bsd-license.php
+  Copyright (c) 2010 - 2015, Intel Corporation. All rights reserved.<BR>
 
-THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+  This program and the accompanying materials are licensed and made available
+  under the terms and conditions of the BSD License which accompanies this
+  distribution.  The full text of the license may be found at
+  http://opensource.org/licenses/bsd-license.php
 
+  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT
+  WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 **/
 
 #include <PiSmm.h>
 #include <Library/SmmCpuFeaturesLib.h>
 #include <Library/BaseLib.h>
 #include <Library/BaseMemoryLib.h>
 #include <Library/PcdLib.h>
 #include <Library/MemoryAllocationLib.h>
 #include <Library/SmmServicesTableLib.h>
 #include <Library/DebugLib.h>
 #include <Register/QemuSmramSaveStateMap.h>
 
 //
 // EFER register LMA bit
 //
 #define LMA BIT10
 
 /**
   The constructor function
 
@@ -70,95 +70,99 @@ SmmCpuFeaturesLibConstructor (
   @param[in] ProcessorInfo   Pointer to an array of EFI_PROCESSOR_INFORMATION
                              structures.  ProcessorInfo[CpuIndex] contains the
                              information for the currently executing CPU.
   @param[in] CpuHotPlugData  Pointer to the CPU_HOT_PLUG_DATA structure that
                              contains the ApidId and SmBase arrays.
 **/
 VOID
 EFIAPI
 SmmCpuFeaturesInitializeProcessor (
   IN UINTN                      CpuIndex,
   IN BOOLEAN                    IsMonarch,
   IN EFI_PROCESSOR_INFORMATION  *ProcessorInfo,
   IN CPU_HOT_PLUG_DATA          *CpuHotPlugData
   )
 {
   QEMU_SMRAM_SAVE_STATE_MAP  *CpuState;
 
   //
   // Configure SMBASE.
   //
-  CpuState = (QEMU_SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
+  CpuState = (QEMU_SMRAM_SAVE_STATE_MAP *)(UINTN)(
+                                            SMM_DEFAULT_SMBASE +
+                                            SMRAM_SAVE_STATE_MAP_OFFSET
+                                            );
   if ((CpuState->x86.SMMRevId & 0xFFFF) == 0) {
     CpuState->x86.SMBASE = (UINT32)CpuHotPlugData->SmBase[CpuIndex];
   } else {
     CpuState->x64.SMBASE = (UINT32)CpuHotPlugData->SmBase[CpuIndex];
   }
 
   //
   // No need to program SMRRs on our virtual platform.
   //
 }
 
 /**
   This function updates the SMRAM save state on the currently executing CPU
   to resume execution at a specific address after an RSM instruction.  This
   function must evaluate the SMRAM save state to determine the execution mode
   the RSM instruction resumes and update the resume execution address with
   either NewInstructionPointer32 or NewInstructionPoint.  The auto HALT restart
   flag in the SMRAM save state must always be cleared.  This function returns
   the value of the instruction pointer from the SMRAM save state that was
   replaced.  If this function returns 0, then the SMRAM save state was not
   modified.
 
   This function is called during the very first SMI on each CPU after
   SmmCpuFeaturesInitializeProcessor() to set a flag in normal execution mode
   to signal that the SMBASE of each CPU has been updated before the default
   SMBASE address is used for the first SMI to the next CPU.
 
   @param[in] CpuIndex                 The index of the CPU to hook.  The value
                                       must be between 0 and the NumberOfCpus
-                                      field in the System Management System Table
-                                      (SMST).
+                                      field in the System Management System
+                                      Table (SMST).
   @param[in] CpuState                 Pointer to SMRAM Save State Map for the
                                       currently executing CPU.
   @param[in] NewInstructionPointer32  Instruction pointer to use if resuming to
                                       32-bit execution mode from 64-bit SMM.
   @param[in] NewInstructionPointer    Instruction pointer to use if resuming to
                                       same execution mode as SMM.
 
   @retval 0    This function did modify the SMRAM save state.
   @retval > 0  The original instruction pointer value from the SMRAM save state
                before it was replaced.
 **/
 UINT64
 EFIAPI
 SmmCpuFeaturesHookReturnFromSmm (
   IN UINTN                 CpuIndex,
   IN SMRAM_SAVE_STATE_MAP  *CpuState,
   IN UINT64                NewInstructionPointer32,
   IN UINT64                NewInstructionPointer
   )
 {
   UINT64                      OriginalInstructionPointer;
-  QEMU_SMRAM_SAVE_STATE_MAP  *CpuSaveState = (QEMU_SMRAM_SAVE_STATE_MAP *)CpuState;
+  QEMU_SMRAM_SAVE_STATE_MAP   *CpuSaveState;
 
+  CpuSaveState = (QEMU_SMRAM_SAVE_STATE_MAP *)CpuState;
   if ((CpuSaveState->x86.SMMRevId & 0xFFFF) == 0) {
     OriginalInstructionPointer = (UINT64)CpuSaveState->x86._EIP;
     CpuSaveState->x86._EIP = (UINT32)NewInstructionPointer;
     //
     // Clear the auto HALT restart flag so the RSM instruction returns
     // program control to the instruction following the HLT instruction.
     //
     if ((CpuSaveState->x86.AutoHALTRestart & BIT0) != 0) {
       CpuSaveState->x86.AutoHALTRestart &= ~BIT0;
     }
   } else {
     OriginalInstructionPointer = CpuSaveState->x64._RIP;
     if ((CpuSaveState->x64.IA32_EFER & LMA) == 0) {
       CpuSaveState->x64._RIP = (UINT32)NewInstructionPointer32;
     } else {
       CpuSaveState->x64._RIP = (UINT32)NewInstructionPointer;
     }
     //
     // Clear the auto HALT restart flag so the RSM instruction returns
     // program control to the instruction following the HLT instruction.
@@ -174,58 +178,59 @@ SmmCpuFeaturesHookReturnFromSmm (
   Hook point in normal execution mode that allows the one CPU that was elected
   as monarch during System Management Mode initialization to perform additional
   initialization actions immediately after all of the CPUs have processed their
   first SMI and called SmmCpuFeaturesInitializeProcessor() relocating SMBASE
   into a buffer in SMRAM and called SmmCpuFeaturesHookReturnFromSmm().
 **/
 VOID
 EFIAPI
 SmmCpuFeaturesSmmRelocationComplete (
   VOID
   )
 {
 }
 
 /**
   Return the size, in bytes, of a custom SMI Handler in bytes.  If 0 is
   returned, then a custom SMI handler is not provided by this library,
   and the default SMI handler must be used.
 
   @retval 0    Use the default SMI handler.
-  @retval > 0  Use the SMI handler installed by SmmCpuFeaturesInstallSmiHandler()
-               The caller is required to allocate enough SMRAM for each CPU to
-               support the size of the custom SMI handler.
+  @retval > 0  Use the SMI handler installed by
+               SmmCpuFeaturesInstallSmiHandler(). The caller is required to
+               allocate enough SMRAM for each CPU to support the size of the
+               custom SMI handler.
 **/
 UINTN
 EFIAPI
 SmmCpuFeaturesGetSmiHandlerSize (
   VOID
   )
 {
   return 0;
 }
 
 /**
-  Install a custom SMI handler for the CPU specified by CpuIndex.  This function
-  is only called if SmmCpuFeaturesGetSmiHandlerSize() returns a size is greater
-  than zero and is called by the CPU that was elected as monarch during System
-  Management Mode initialization.
+  Install a custom SMI handler for the CPU specified by CpuIndex.  This
+  function is only called if SmmCpuFeaturesGetSmiHandlerSize() returns a size
+  is greater than zero and is called by the CPU that was elected as monarch
+  during System Management Mode initialization.
 
   @param[in] CpuIndex   The index of the CPU to install the custom SMI handler.
                         The value must be between 0 and the NumberOfCpus field
                         in the System Management System Table (SMST).
   @param[in] SmBase     The SMBASE address for the CPU specified by CpuIndex.
   @param[in] SmiStack   The stack to use when an SMI is processed by the
                         the CPU specified by CpuIndex.
   @param[in] StackSize  The size, in bytes, if the stack used when an SMI is
                         processed by the CPU specified by CpuIndex.
   @param[in] GdtBase    The base address of the GDT to use when an SMI is
                         processed by the CPU specified by CpuIndex.
   @param[in] GdtSize    The size, in bytes, of the GDT used when an SMI is
                         processed by the CPU specified by CpuIndex.
   @param[in] IdtBase    The base address of the IDT to use when an SMI is
                         processed by the CPU specified by CpuIndex.
   @param[in] IdtSize    The size, in bytes, of the IDT used when an SMI is
                         processed by the CPU specified by CpuIndex.
   @param[in] Cr3        The base address of the page tables to use when an SMI
                         is processed by the CPU specified by CpuIndex.
 **/
@@ -246,93 +251,93 @@ SmmCpuFeaturesInstallSmiHandler (
 }
 
 /**
   Determines if MTRR registers must be configured to set SMRAM cache-ability
   when executing in System Management Mode.
 
   @retval TRUE   MTRR registers must be configured to set SMRAM cache-ability.
   @retval FALSE  MTRR registers do not need to be configured to set SMRAM
                  cache-ability.
 **/
 BOOLEAN
 EFIAPI
 SmmCpuFeaturesNeedConfigureMtrrs (
   VOID
   )
 {
   return FALSE;
 }
 
 /**
-  Disable SMRR register if SMRR is supported and SmmCpuFeaturesNeedConfigureMtrrs()
-  returns TRUE.
+  Disable SMRR register if SMRR is supported and
+  SmmCpuFeaturesNeedConfigureMtrrs() returns TRUE.
 **/
 VOID
 EFIAPI
 SmmCpuFeaturesDisableSmrr (
   VOID
   )
 {
   //
   // No SMRR support, nothing to do
   //
 }
 
 /**
-  Enable SMRR register if SMRR is supported and SmmCpuFeaturesNeedConfigureMtrrs()
-  returns TRUE.
+  Enable SMRR register if SMRR is supported and
+  SmmCpuFeaturesNeedConfigureMtrrs() returns TRUE.
 **/
 VOID
 EFIAPI
 SmmCpuFeaturesReenableSmrr (
   VOID
   )
 {
   //
   // No SMRR support, nothing to do
   //
 }
 
 /**
   Processor specific hook point each time a CPU enters System Management Mode.
 
   @param[in] CpuIndex  The index of the CPU that has entered SMM.  The value
                        must be between 0 and the NumberOfCpus field in the
                        System Management System Table (SMST).
 **/
 VOID
 EFIAPI
 SmmCpuFeaturesRendezvousEntry (
   IN UINTN  CpuIndex
   )
 {
   //
   // No SMRR support, nothing to do
   //
 }
 
 /**
   Processor specific hook point each time a CPU exits System Management Mode.
 
-  @param[in] CpuIndex  The index of the CPU that is exiting SMM.  The value must
-                       be between 0 and the NumberOfCpus field in the System
-                       Management System Table (SMST).
+  @param[in] CpuIndex  The index of the CPU that is exiting SMM.  The value
+                       must be between 0 and the NumberOfCpus field in the
+                       System Management System Table (SMST).
 **/
 VOID
 EFIAPI
 SmmCpuFeaturesRendezvousExit (
   IN UINTN  CpuIndex
   )
 {
 }
 
 /**
   Check to see if an SMM register is supported by a specified CPU.
 
   @param[in] CpuIndex  The index of the CPU to check for SMM register support.
                        The value must be between 0 and the NumberOfCpus field
                        in the System Management System Table (SMST).
   @param[in] RegName   Identifies the SMM register to check for support.
 
   @retval TRUE   The SMM register specified by RegName is supported by the CPU
                  specified by CpuIndex.
   @retval FALSE  The SMM register specified by RegName is not supported by the
@@ -382,263 +387,606 @@ SmmCpuFeaturesGetSmmRegister (
 
   @param[in] CpuIndex  The index of the CPU to write the SMM register.  The
                        value must be between 0 and the NumberOfCpus field in
                        the System Management System Table (SMST).
   @param[in] RegName   Identifies the SMM register to write.
                        registers are read-only.
   @param[in] Value     The value to write to the SMM register.
 **/
 VOID
 EFIAPI
 SmmCpuFeaturesSetSmmRegister (
   IN UINTN         CpuIndex,
   IN SMM_REG_NAME  RegName,
   IN UINT64        Value
   )
 {
   ASSERT (FALSE);
 }
 
 ///
-/// Macro used to simplify the lookup table entries of type CPU_SMM_SAVE_STATE_LOOKUP_ENTRY
+/// Macro used to simplify the lookup table entries of type
+/// CPU_SMM_SAVE_STATE_LOOKUP_ENTRY
 ///
 #define SMM_CPU_OFFSET(Field) OFFSET_OF (QEMU_SMRAM_SAVE_STATE_MAP, Field)
 
 ///
-/// Macro used to simplify the lookup table entries of type CPU_SMM_SAVE_STATE_REGISTER_RANGE
+/// Macro used to simplify the lookup table entries of type
+/// CPU_SMM_SAVE_STATE_REGISTER_RANGE
 ///
 #define SMM_REGISTER_RANGE(Start, End) { Start, End, End - Start + 1 }
 
 ///
 /// Structure used to describe a range of registers
 ///
 typedef struct {
   EFI_SMM_SAVE_STATE_REGISTER  Start;
   EFI_SMM_SAVE_STATE_REGISTER  End;
   UINTN                        Length;
 } CPU_SMM_SAVE_STATE_REGISTER_RANGE;
 
 ///
 /// Structure used to build a lookup table to retrieve the widths and offsets
 /// associated with each supported EFI_SMM_SAVE_STATE_REGISTER value
 ///
 
 #define SMM_SAVE_STATE_REGISTER_FIRST_INDEX             1
 
 typedef struct {
   UINT8   Width32;
   UINT8   Width64;
   UINT16  Offset32;
   UINT16  Offset64Lo;
   UINT16  Offset64Hi;
   BOOLEAN Writeable;
 } CPU_SMM_SAVE_STATE_LOOKUP_ENTRY;
 
 ///
-/// Table used by GetRegisterIndex() to convert an EFI_SMM_SAVE_STATE_REGISTER 
+/// Table used by GetRegisterIndex() to convert an EFI_SMM_SAVE_STATE_REGISTER
 /// value to an index into a table of type CPU_SMM_SAVE_STATE_LOOKUP_ENTRY
 ///
 static CONST CPU_SMM_SAVE_STATE_REGISTER_RANGE mSmmCpuRegisterRanges[] = {
-  SMM_REGISTER_RANGE (EFI_SMM_SAVE_STATE_REGISTER_GDTBASE, EFI_SMM_SAVE_STATE_REGISTER_LDTINFO),
-  SMM_REGISTER_RANGE (EFI_SMM_SAVE_STATE_REGISTER_ES,      EFI_SMM_SAVE_STATE_REGISTER_RIP),
-  SMM_REGISTER_RANGE (EFI_SMM_SAVE_STATE_REGISTER_RFLAGS,  EFI_SMM_SAVE_STATE_REGISTER_CR4),
+  SMM_REGISTER_RANGE (
+    EFI_SMM_SAVE_STATE_REGISTER_GDTBASE,
+    EFI_SMM_SAVE_STATE_REGISTER_LDTINFO
+    ),
+  SMM_REGISTER_RANGE (
+    EFI_SMM_SAVE_STATE_REGISTER_ES,
+    EFI_SMM_SAVE_STATE_REGISTER_RIP
+    ),
+  SMM_REGISTER_RANGE (
+    EFI_SMM_SAVE_STATE_REGISTER_RFLAGS,
+    EFI_SMM_SAVE_STATE_REGISTER_CR4
+    ),
   { (EFI_SMM_SAVE_STATE_REGISTER)0, (EFI_SMM_SAVE_STATE_REGISTER)0, 0 }
 };
 
 ///
-/// Lookup table used to retrieve the widths and offsets associated with each 
-/// supported EFI_SMM_SAVE_STATE_REGISTER value 
+/// Lookup table used to retrieve the widths and offsets associated with each
+/// supported EFI_SMM_SAVE_STATE_REGISTER value
 ///
 static CONST CPU_SMM_SAVE_STATE_LOOKUP_ENTRY mSmmCpuWidthOffset[] = {
-  {0, 0, 0, 0, 0, FALSE},                                                                                                     //  Reserved
+  {
+    0,                                    // Width32
+    0,                                    // Width64
+    0,                                    // Offset32
+    0,                                    // Offset64Lo
+    0,                                    // Offset64Hi
+    FALSE                                 // Writeable
+  }, // Reserved
 
   //
   // CPU Save State registers defined in PI SMM CPU Protocol.
   //
-  {0, 8, 0                            , SMM_CPU_OFFSET (x64._GDTRBase) , SMM_CPU_OFFSET (x64._GDTRBase)  + 4, FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_GDTBASE  = 4
-  {0, 8, 0                            , SMM_CPU_OFFSET (x64._IDTRBase) , SMM_CPU_OFFSET (x64._IDTRBase)  + 4, FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_IDTBASE  = 5
-  {0, 8, 0                            , SMM_CPU_OFFSET (x64._LDTRBase) , SMM_CPU_OFFSET (x64._LDTRBase)  + 4, FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_LDTBASE  = 6
-  {0, 0, 0                            , SMM_CPU_OFFSET (x64._GDTRLimit), SMM_CPU_OFFSET (x64._GDTRLimit) + 4, FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_GDTLIMIT = 7
-  {0, 0, 0                            , SMM_CPU_OFFSET (x64._IDTRLimit), SMM_CPU_OFFSET (x64._IDTRLimit) + 4, FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_IDTLIMIT = 8
-  {0, 0, 0                            , SMM_CPU_OFFSET (x64._LDTRLimit), SMM_CPU_OFFSET (x64._LDTRLimit) + 4, FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_LDTLIMIT = 9
-  {0, 0, 0                            , 0                              , 0                               + 4, FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_LDTINFO  = 10
-
-  {4, 4, SMM_CPU_OFFSET (x86._ES)     , SMM_CPU_OFFSET (x64._ES)     , 0                               , FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_ES       = 20
-  {4, 4, SMM_CPU_OFFSET (x86._CS)     , SMM_CPU_OFFSET (x64._CS)     , 0                               , FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_CS       = 21
-  {4, 4, SMM_CPU_OFFSET (x86._SS)     , SMM_CPU_OFFSET (x64._SS)     , 0                               , FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_SS       = 22
-  {4, 4, SMM_CPU_OFFSET (x86._DS)     , SMM_CPU_OFFSET (x64._DS)     , 0                               , FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_DS       = 23
-  {4, 4, SMM_CPU_OFFSET (x86._FS)     , SMM_CPU_OFFSET (x64._FS)     , 0                               , FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_FS       = 24
-  {4, 4, SMM_CPU_OFFSET (x86._GS)     , SMM_CPU_OFFSET (x64._GS)     , 0                               , FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_GS       = 25
-  {0, 4, 0                            , SMM_CPU_OFFSET (x64._LDTR)   , 0                               , FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_LDTR_SEL = 26
-  {4, 4, SMM_CPU_OFFSET (x86._TR)     , SMM_CPU_OFFSET (x64._TR)     , 0                               , FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_TR_SEL   = 27
-  {4, 8, SMM_CPU_OFFSET (x86._DR7)    , SMM_CPU_OFFSET (x64._DR7)    , SMM_CPU_OFFSET (x64._DR7)    + 4, FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_DR7      = 28
-  {4, 8, SMM_CPU_OFFSET (x86._DR6)    , SMM_CPU_OFFSET (x64._DR6)    , SMM_CPU_OFFSET (x64._DR6)    + 4, FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_DR6      = 29
-  {0, 8, 0                            , SMM_CPU_OFFSET (x64._R8)     , SMM_CPU_OFFSET (x64._R8)     + 4, TRUE },  //  EFI_SMM_SAVE_STATE_REGISTER_R8       = 30
-  {0, 8, 0                            , SMM_CPU_OFFSET (x64._R9)     , SMM_CPU_OFFSET (x64._R9)     + 4, TRUE },  //  EFI_SMM_SAVE_STATE_REGISTER_R9       = 31
-  {0, 8, 0                            , SMM_CPU_OFFSET (x64._R10)    , SMM_CPU_OFFSET (x64._R10)    + 4, TRUE },  //  EFI_SMM_SAVE_STATE_REGISTER_R10      = 32
-  {0, 8, 0                            , SMM_CPU_OFFSET (x64._R11)    , SMM_CPU_OFFSET (x64._R11)    + 4, TRUE },  //  EFI_SMM_SAVE_STATE_REGISTER_R11      = 33
-  {0, 8, 0                            , SMM_CPU_OFFSET (x64._R12)    , SMM_CPU_OFFSET (x64._R12)    + 4, TRUE },  //  EFI_SMM_SAVE_STATE_REGISTER_R12      = 34
-  {0, 8, 0                            , SMM_CPU_OFFSET (x64._R13)    , SMM_CPU_OFFSET (x64._R13)    + 4, TRUE },  //  EFI_SMM_SAVE_STATE_REGISTER_R13      = 35
-  {0, 8, 0                            , SMM_CPU_OFFSET (x64._R14)    , SMM_CPU_OFFSET (x64._R14)    + 4, TRUE },  //  EFI_SMM_SAVE_STATE_REGISTER_R14      = 36
-  {0, 8, 0                            , SMM_CPU_OFFSET (x64._R15)    , SMM_CPU_OFFSET (x64._R15)    + 4, TRUE },  //  EFI_SMM_SAVE_STATE_REGISTER_R15      = 37
-  {4, 8, SMM_CPU_OFFSET (x86._EAX)    , SMM_CPU_OFFSET (x64._RAX)    , SMM_CPU_OFFSET (x64._RAX)    + 4, TRUE },  //  EFI_SMM_SAVE_STATE_REGISTER_RAX      = 38
-  {4, 8, SMM_CPU_OFFSET (x86._EBX)    , SMM_CPU_OFFSET (x64._RBX)    , SMM_CPU_OFFSET (x64._RBX)    + 4, TRUE },  //  EFI_SMM_SAVE_STATE_REGISTER_RBX      = 39
-  {4, 8, SMM_CPU_OFFSET (x86._ECX)    , SMM_CPU_OFFSET (x64._RCX)    , SMM_CPU_OFFSET (x64._RCX)    + 4, TRUE },  //  EFI_SMM_SAVE_STATE_REGISTER_RCX      = 40
-  {4, 8, SMM_CPU_OFFSET (x86._EDX)    , SMM_CPU_OFFSET (x64._RDX)    , SMM_CPU_OFFSET (x64._RDX)    + 4, TRUE },  //  EFI_SMM_SAVE_STATE_REGISTER_RDX      = 41
-  {4, 8, SMM_CPU_OFFSET (x86._ESP)    , SMM_CPU_OFFSET (x64._RSP)    , SMM_CPU_OFFSET (x64._RSP)    + 4, TRUE },  //  EFI_SMM_SAVE_STATE_REGISTER_RSP      = 42
-  {4, 8, SMM_CPU_OFFSET (x86._EBP)    , SMM_CPU_OFFSET (x64._RBP)    , SMM_CPU_OFFSET (x64._RBP)    + 4, TRUE },  //  EFI_SMM_SAVE_STATE_REGISTER_RBP      = 43
-  {4, 8, SMM_CPU_OFFSET (x86._ESI)    , SMM_CPU_OFFSET (x64._RSI)    , SMM_CPU_OFFSET (x64._RSI)    + 4, TRUE },  //  EFI_SMM_SAVE_STATE_REGISTER_RSI      = 44
-  {4, 8, SMM_CPU_OFFSET (x86._EDI)    , SMM_CPU_OFFSET (x64._RDI)    , SMM_CPU_OFFSET (x64._RDI)    + 4, TRUE },  //  EFI_SMM_SAVE_STATE_REGISTER_RDI      = 45
-  {4, 8, SMM_CPU_OFFSET (x86._EIP)    , SMM_CPU_OFFSET (x64._RIP)    , SMM_CPU_OFFSET (x64._RIP)    + 4, TRUE },  //  EFI_SMM_SAVE_STATE_REGISTER_RIP      = 46
-
-  {4, 8, SMM_CPU_OFFSET (x86._EFLAGS) , SMM_CPU_OFFSET (x64._RFLAGS) , SMM_CPU_OFFSET (x64._RFLAGS) + 4, TRUE },  //  EFI_SMM_SAVE_STATE_REGISTER_RFLAGS   = 51
-  {4, 8, SMM_CPU_OFFSET (x86._CR0)    , SMM_CPU_OFFSET (x64._CR0)    , SMM_CPU_OFFSET (x64._CR0)    + 4, FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_CR0      = 52
-  {4, 8, SMM_CPU_OFFSET (x86._CR3)    , SMM_CPU_OFFSET (x64._CR3)    , SMM_CPU_OFFSET (x64._CR3)    + 4, FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_CR3      = 53
-  {0, 4, 0                            , SMM_CPU_OFFSET (x64._CR4)    , SMM_CPU_OFFSET (x64._CR4)    + 4, FALSE},  //  EFI_SMM_SAVE_STATE_REGISTER_CR4      = 54
+  {
+    0,                                    // Width32
+    8,                                    // Width64
+    0,                                    // Offset32
+    SMM_CPU_OFFSET (x64._GDTRBase),       // Offset64Lo
+    SMM_CPU_OFFSET (x64._GDTRBase) + 4,   // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_GDTBASE = 4
+
+  {
+    0,                                    // Width32
+    8,                                    // Width64
+    0,                                    // Offset32
+    SMM_CPU_OFFSET (x64._IDTRBase),       // Offset64Lo
+    SMM_CPU_OFFSET (x64._IDTRBase) + 4,   // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_IDTBASE = 5
+
+  {
+    0,                                    // Width32
+    8,                                    // Width64
+    0,                                    // Offset32
+    SMM_CPU_OFFSET (x64._LDTRBase),       // Offset64Lo
+    SMM_CPU_OFFSET (x64._LDTRBase) + 4,   // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_LDTBASE = 6
+
+  {
+    0,                                    // Width32
+    0,                                    // Width64
+    0,                                    // Offset32
+    SMM_CPU_OFFSET (x64._GDTRLimit),      // Offset64Lo
+    SMM_CPU_OFFSET (x64._GDTRLimit) + 4,  // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_GDTLIMIT = 7
+
+  {
+    0,                                    // Width32
+    0,                                    // Width64
+    0,                                    // Offset32
+    SMM_CPU_OFFSET (x64._IDTRLimit),      // Offset64Lo
+    SMM_CPU_OFFSET (x64._IDTRLimit) + 4,  // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_IDTLIMIT = 8
+
+  {
+    0,                                    // Width32
+    0,                                    // Width64
+    0,                                    // Offset32
+    SMM_CPU_OFFSET (x64._LDTRLimit),      // Offset64Lo
+    SMM_CPU_OFFSET (x64._LDTRLimit) + 4,  // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_LDTLIMIT = 9
+
+  {
+    0,                                    // Width32
+    0,                                    // Width64
+    0,                                    // Offset32
+    0,                                    // Offset64Lo
+    0 + 4,                                // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_LDTINFO = 10
+
+  {
+    4,                                    // Width32
+    4,                                    // Width64
+    SMM_CPU_OFFSET (x86._ES),             // Offset32
+    SMM_CPU_OFFSET (x64._ES),             // Offset64Lo
+    0,                                    // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_ES = 20
+
+  {
+    4,                                    // Width32
+    4,                                    // Width64
+    SMM_CPU_OFFSET (x86._CS),             // Offset32
+    SMM_CPU_OFFSET (x64._CS),             // Offset64Lo
+    0,                                    // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_CS = 21
+
+  {
+    4,                                    // Width32
+    4,                                    // Width64
+    SMM_CPU_OFFSET (x86._SS),             // Offset32
+    SMM_CPU_OFFSET (x64._SS),             // Offset64Lo
+    0,                                    // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_SS = 22
+
+  {
+    4,                                    // Width32
+    4,                                    // Width64
+    SMM_CPU_OFFSET (x86._DS),             // Offset32
+    SMM_CPU_OFFSET (x64._DS),             // Offset64Lo
+    0,                                    // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_DS = 23
+
+  {
+    4,                                    // Width32
+    4,                                    // Width64
+    SMM_CPU_OFFSET (x86._FS),             // Offset32
+    SMM_CPU_OFFSET (x64._FS),             // Offset64Lo
+    0,                                    // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_FS = 24
+
+  {
+    4,                                    // Width32
+    4,                                    // Width64
+    SMM_CPU_OFFSET (x86._GS),             // Offset32
+    SMM_CPU_OFFSET (x64._GS),             // Offset64Lo
+    0,                                    // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_GS = 25
+
+  {
+    0,                                    // Width32
+    4,                                    // Width64
+    0,                                    // Offset32
+    SMM_CPU_OFFSET (x64._LDTR),           // Offset64Lo
+    0,                                    // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_LDTR_SEL = 26
+
+  {
+    4,                                    // Width32
+    4,                                    // Width64
+    SMM_CPU_OFFSET (x86._TR),             // Offset32
+    SMM_CPU_OFFSET (x64._TR),             // Offset64Lo
+    0,                                    // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_TR_SEL = 27
+
+  {
+    4,                                    // Width32
+    8,                                    // Width64
+    SMM_CPU_OFFSET (x86._DR7),            // Offset32
+    SMM_CPU_OFFSET (x64._DR7),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._DR7) + 4,        // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_DR7 = 28
+
+  {
+    4,                                    // Width32
+    8,                                    // Width64
+    SMM_CPU_OFFSET (x86._DR6),            // Offset32
+    SMM_CPU_OFFSET (x64._DR6),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._DR6) + 4,        // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_DR6 = 29
+
+  {
+    0,                                    // Width32
+    8,                                    // Width64
+    0,                                    // Offset32
+    SMM_CPU_OFFSET (x64._R8),             // Offset64Lo
+    SMM_CPU_OFFSET (x64._R8) + 4,         // Offset64Hi
+    TRUE                                  // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_R8 = 30
+
+  {
+    0,                                    // Width32
+    8,                                    // Width64
+    0,                                    // Offset32
+    SMM_CPU_OFFSET (x64._R9),             // Offset64Lo
+    SMM_CPU_OFFSET (x64._R9) + 4,         // Offset64Hi
+    TRUE                                  // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_R9 = 31
+
+  {
+    0,                                    // Width32
+    8,                                    // Width64
+    0,                                    // Offset32
+    SMM_CPU_OFFSET (x64._R10),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._R10) + 4,        // Offset64Hi
+    TRUE                                  // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_R10 = 32
+
+  {
+    0,                                    // Width32
+    8,                                    // Width64
+    0,                                    // Offset32
+    SMM_CPU_OFFSET (x64._R11),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._R11) + 4,        // Offset64Hi
+    TRUE                                  // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_R11 = 33
+
+  {
+    0,                                    // Width32
+    8,                                    // Width64
+    0,                                    // Offset32
+    SMM_CPU_OFFSET (x64._R12),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._R12) + 4,        // Offset64Hi
+    TRUE                                  // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_R12 = 34
+
+  {
+    0,                                    // Width32
+    8,                                    // Width64
+    0,                                    // Offset32
+    SMM_CPU_OFFSET (x64._R13),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._R13) + 4,        // Offset64Hi
+    TRUE                                  // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_R13 = 35
+
+  {
+    0,                                    // Width32
+    8,                                    // Width64
+    0,                                    // Offset32
+    SMM_CPU_OFFSET (x64._R14),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._R14) + 4,        // Offset64Hi
+    TRUE                                  // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_R14 = 36
+
+  {
+    0,                                    // Width32
+    8,                                    // Width64
+    0,                                    // Offset32
+    SMM_CPU_OFFSET (x64._R15),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._R15) + 4,        // Offset64Hi
+    TRUE                                  // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_R15 = 37
+
+  {
+    4,                                    // Width32
+    8,                                    // Width64
+    SMM_CPU_OFFSET (x86._EAX),            // Offset32
+    SMM_CPU_OFFSET (x64._RAX),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._RAX) + 4,        // Offset64Hi
+    TRUE                                  // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_RAX = 38
+
+  {
+    4,                                    // Width32
+    8,                                    // Width64
+    SMM_CPU_OFFSET (x86._EBX),            // Offset32
+    SMM_CPU_OFFSET (x64._RBX),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._RBX) + 4,        // Offset64Hi
+    TRUE                                  // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_RBX = 39
+
+  {
+    4,                                    // Width32
+    8,                                    // Width64
+    SMM_CPU_OFFSET (x86._ECX),            // Offset32
+    SMM_CPU_OFFSET (x64._RCX),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._RCX) + 4,        // Offset64Hi
+    TRUE                                  // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_RCX = 40
+
+  {
+    4,                                    // Width32
+    8,                                    // Width64
+    SMM_CPU_OFFSET (x86._EDX),            // Offset32
+    SMM_CPU_OFFSET (x64._RDX),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._RDX) + 4,        // Offset64Hi
+    TRUE                                  // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_RDX = 41
+
+  {
+    4,                                    // Width32
+    8,                                    // Width64
+    SMM_CPU_OFFSET (x86._ESP),            // Offset32
+    SMM_CPU_OFFSET (x64._RSP),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._RSP) + 4,        // Offset64Hi
+    TRUE                                  // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_RSP = 42
+
+  {
+    4,                                    // Width32
+    8,                                    // Width64
+    SMM_CPU_OFFSET (x86._EBP),            // Offset32
+    SMM_CPU_OFFSET (x64._RBP),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._RBP) + 4,        // Offset64Hi
+    TRUE                                  // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_RBP = 43
+
+  {
+    4,                                    // Width32
+    8,                                    // Width64
+    SMM_CPU_OFFSET (x86._ESI),            // Offset32
+    SMM_CPU_OFFSET (x64._RSI),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._RSI) + 4,        // Offset64Hi
+    TRUE                                  // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_RSI = 44
+
+  {
+    4,                                    // Width32
+    8,                                    // Width64
+    SMM_CPU_OFFSET (x86._EDI),            // Offset32
+    SMM_CPU_OFFSET (x64._RDI),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._RDI) + 4,        // Offset64Hi
+    TRUE                                  // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_RDI = 45
+
+  {
+    4,                                    // Width32
+    8,                                    // Width64
+    SMM_CPU_OFFSET (x86._EIP),            // Offset32
+    SMM_CPU_OFFSET (x64._RIP),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._RIP) + 4,        // Offset64Hi
+    TRUE                                  // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_RIP = 46
+
+  {
+    4,                                    // Width32
+    8,                                    // Width64
+    SMM_CPU_OFFSET (x86._EFLAGS),         // Offset32
+    SMM_CPU_OFFSET (x64._RFLAGS),         // Offset64Lo
+    SMM_CPU_OFFSET (x64._RFLAGS) + 4,     // Offset64Hi
+    TRUE                                  // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_RFLAGS = 51
+
+  {
+    4,                                    // Width32
+    8,                                    // Width64
+    SMM_CPU_OFFSET (x86._CR0),            // Offset32
+    SMM_CPU_OFFSET (x64._CR0),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._CR0) + 4,        // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_CR0 = 52
+
+  {
+    4,                                    // Width32
+    8,                                    // Width64
+    SMM_CPU_OFFSET (x86._CR3),            // Offset32
+    SMM_CPU_OFFSET (x64._CR3),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._CR3) + 4,        // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_CR3 = 53
+
+  {
+    0,                                    // Width32
+    4,                                    // Width64
+    0,                                    // Offset32
+    SMM_CPU_OFFSET (x64._CR4),            // Offset64Lo
+    SMM_CPU_OFFSET (x64._CR4) + 4,        // Offset64Hi
+    FALSE                                 // Writeable
+  }, // EFI_SMM_SAVE_STATE_REGISTER_CR4 = 54
 };
 
 //
 // No support for I/O restart
 //
 
 /**
   Read information from the CPU save state.
 
   @param  Register  Specifies the CPU register to read form the save state.
 
   @retval 0   Register is not valid
   @retval >0  Index into mSmmCpuWidthOffset[] associated with Register
 
 **/
 static UINTN
 GetRegisterIndex (
   IN EFI_SMM_SAVE_STATE_REGISTER  Register
   )
 {
   UINTN  Index;
   UINTN  Offset;
 
-  for (Index = 0, Offset = SMM_SAVE_STATE_REGISTER_FIRST_INDEX; mSmmCpuRegisterRanges[Index].Length != 0; Index++) {
-    if (Register >= mSmmCpuRegisterRanges[Index].Start && Register <= mSmmCpuRegisterRanges[Index].End) {
+  for (Index = 0, Offset = SMM_SAVE_STATE_REGISTER_FIRST_INDEX;
+       mSmmCpuRegisterRanges[Index].Length != 0;
+       Index++) {
+    if (Register >= mSmmCpuRegisterRanges[Index].Start &&
+        Register <= mSmmCpuRegisterRanges[Index].End) {
       return Register - mSmmCpuRegisterRanges[Index].Start + Offset;
     }
     Offset += mSmmCpuRegisterRanges[Index].Length;
   }
   return 0;
 }
 
 /**
   Read a CPU Save State register on the target processor.
 
-  This function abstracts the differences that whether the CPU Save State register is in the 
-  IA32 CPU Save State Map or X64 CPU Save State Map.
+  This function abstracts the differences that whether the CPU Save State
+  register is in the IA32 CPU Save State Map or X64 CPU Save State Map.
 
-  This function supports reading a CPU Save State register in SMBase relocation handler.
+  This function supports reading a CPU Save State register in SMBase relocation
+  handler.
 
-  @param[in]  CpuIndex       Specifies the zero-based index of the CPU save state.
+  @param[in]  CpuIndex       Specifies the zero-based index of the CPU save
+                             state.
   @param[in]  RegisterIndex  Index into mSmmCpuWidthOffset[] look up table.
-  @param[in]  Width          The number of bytes to read from the CPU save state.
-  @param[out] Buffer         Upon return, this holds the CPU register value read from the save state.
+  @param[in]  Width          The number of bytes to read from the CPU save
+                             state.
+  @param[out] Buffer         Upon return, this holds the CPU register value
+                             read from the save state.
 
   @retval EFI_SUCCESS           The register was read from Save State.
-  @retval EFI_NOT_FOUND         The register is not defined for the Save State of Processor.
+  @retval EFI_NOT_FOUND         The register is not defined for the Save State
+                                of Processor.
   @retval EFI_INVALID_PARAMTER  This or Buffer is NULL.
 
 **/
 static EFI_STATUS
 ReadSaveStateRegisterByIndex (
   IN UINTN   CpuIndex,
   IN UINTN   RegisterIndex,
   IN UINTN   Width,
   OUT VOID   *Buffer
   )
 {
   QEMU_SMRAM_SAVE_STATE_MAP  *CpuSaveState;
 
   CpuSaveState = (QEMU_SMRAM_SAVE_STATE_MAP *)gSmst->CpuSaveState[CpuIndex];
 
   if ((CpuSaveState->x86.SMMRevId & 0xFFFF) == 0) {
     //
-    // If 32-bit mode width is zero, then the specified register can not be accessed
+    // If 32-bit mode width is zero, then the specified register can not be
+    // accessed
     //
     if (mSmmCpuWidthOffset[RegisterIndex].Width32 == 0) {
       return EFI_NOT_FOUND;
     }
 
     //
-    // If Width is bigger than the 32-bit mode width, then the specified register can not be accessed
+    // If Width is bigger than the 32-bit mode width, then the specified
+    // register can not be accessed
     //
     if (Width > mSmmCpuWidthOffset[RegisterIndex].Width32) {
       return EFI_INVALID_PARAMETER;
     }
 
     //
     // Write return buffer
     //
     ASSERT(CpuSaveState != NULL);
-    CopyMem(Buffer, (UINT8 *)CpuSaveState + mSmmCpuWidthOffset[RegisterIndex].Offset32, Width);
+    CopyMem (
+      Buffer,
+      (UINT8 *)CpuSaveState + mSmmCpuWidthOffset[RegisterIndex].Offset32,
+      Width
+      );
   } else {
     //
-    // If 64-bit mode width is zero, then the specified register can not be accessed
+    // If 64-bit mode width is zero, then the specified register can not be
+    // accessed
     //
     if (mSmmCpuWidthOffset[RegisterIndex].Width64 == 0) {
       return EFI_NOT_FOUND;
     }
 
     //
-    // If Width is bigger than the 64-bit mode width, then the specified register can not be accessed
+    // If Width is bigger than the 64-bit mode width, then the specified
+    // register can not be accessed
     //
     if (Width > mSmmCpuWidthOffset[RegisterIndex].Width64) {
       return EFI_INVALID_PARAMETER;
     }
 
     //
     // Write lower 32-bits of return buffer
     //
-    CopyMem(Buffer, (UINT8 *)CpuSaveState + mSmmCpuWidthOffset[RegisterIndex].Offset64Lo, MIN(4, Width));
+    CopyMem (
+      Buffer,
+      (UINT8 *)CpuSaveState + mSmmCpuWidthOffset[RegisterIndex].Offset64Lo,
+      MIN (4, Width)
+      );
     if (Width >= 4) {
       //
       // Write upper 32-bits of return buffer
       //
-      CopyMem((UINT8 *)Buffer + 4, (UINT8 *)CpuSaveState + mSmmCpuWidthOffset[RegisterIndex].Offset64Hi, Width - 4);
+      CopyMem (
+        (UINT8 *)Buffer + 4,
+        (UINT8 *)CpuSaveState + mSmmCpuWidthOffset[RegisterIndex].Offset64Hi,
+        Width - 4
+        );
     }
   }
   return EFI_SUCCESS;
 }
 
 /**
   Read an SMM Save State register on the target processor.  If this function
   returns EFI_UNSUPPORTED, then the caller is responsible for reading the
   SMM Save Sate register.
 
   @param[in]  CpuIndex  The index of the CPU to read the SMM Save State.  The
                         value must be between 0 and the NumberOfCpus field in
                         the System Management System Table (SMST).
   @param[in]  Register  The SMM Save State register to read.
   @param[in]  Width     The number of bytes to read from the CPU save state.
   @param[out] Buffer    Upon return, this holds the CPU register value read
                         from the save state.
 
   @retval EFI_SUCCESS           The register was read from Save State.
   @retval EFI_INVALID_PARAMTER  Buffer is NULL.
-  @retval EFI_UNSUPPORTED       This function does not support reading Register.
-
+  @retval EFI_UNSUPPORTED       This function does not support reading
+                                Register.
 **/
 EFI_STATUS
 EFIAPI
 SmmCpuFeaturesReadSaveStateRegister (
   IN  UINTN                        CpuIndex,
   IN  EFI_SMM_SAVE_STATE_REGISTER  Register,
   IN  UINTN                        Width,
   OUT VOID                         *Buffer
   )
 {
   UINTN                       RegisterIndex;
   QEMU_SMRAM_SAVE_STATE_MAP  *CpuSaveState;
 
   //
   // Check for special EFI_SMM_SAVE_STATE_REGISTER_LMA
   //
   if (Register == EFI_SMM_SAVE_STATE_REGISTER_LMA) {
     //
     // Only byte access is supported for this register
     //
@@ -657,178 +1005,202 @@ SmmCpuFeaturesReadSaveStateRegister (
       *(UINT8 *)Buffer = 64;
     }
 
     return EFI_SUCCESS;
   }
 
   //
   // Check for special EFI_SMM_SAVE_STATE_REGISTER_IO
   //
   if (Register == EFI_SMM_SAVE_STATE_REGISTER_IO) {
     return EFI_NOT_FOUND;
   }
 
   //
   // Convert Register to a register lookup table index.  Let
   // PiSmmCpuDxeSmm implement other special registers (currently
   // there is only EFI_SMM_SAVE_STATE_REGISTER_PROCESSOR_ID).
   //
   RegisterIndex = GetRegisterIndex (Register);
   if (RegisterIndex == 0) {
-    return Register < EFI_SMM_SAVE_STATE_REGISTER_IO ? EFI_NOT_FOUND : EFI_UNSUPPORTED;
+    return (Register < EFI_SMM_SAVE_STATE_REGISTER_IO ?
+            EFI_NOT_FOUND :
+            EFI_UNSUPPORTED);
   }
 
   return ReadSaveStateRegisterByIndex (CpuIndex, RegisterIndex, Width, Buffer);
 }
 
 /**
   Writes an SMM Save State register on the target processor.  If this function
   returns EFI_UNSUPPORTED, then the caller is responsible for writing the
   SMM Save Sate register.
 
   @param[in] CpuIndex  The index of the CPU to write the SMM Save State.  The
                        value must be between 0 and the NumberOfCpus field in
                        the System Management System Table (SMST).
   @param[in] Register  The SMM Save State register to write.
   @param[in] Width     The number of bytes to write to the CPU save state.
   @param[in] Buffer    Upon entry, this holds the new CPU register value.
 
   @retval EFI_SUCCESS           The register was written to Save State.
   @retval EFI_INVALID_PARAMTER  Buffer is NULL.
-  @retval EFI_UNSUPPORTED       This function does not support writing Register.
+  @retval EFI_UNSUPPORTED       This function does not support writing
+                                Register.
 **/
 EFI_STATUS
 EFIAPI
 SmmCpuFeaturesWriteSaveStateRegister (
   IN UINTN                        CpuIndex,
   IN EFI_SMM_SAVE_STATE_REGISTER  Register,
   IN UINTN                        Width,
   IN CONST VOID                   *Buffer
   )
 {
   UINTN                       RegisterIndex;
   QEMU_SMRAM_SAVE_STATE_MAP  *CpuSaveState;
 
   //
   // Writes to EFI_SMM_SAVE_STATE_REGISTER_LMA are ignored
   //
   if (Register == EFI_SMM_SAVE_STATE_REGISTER_LMA) {
     return EFI_SUCCESS;
   }
 
   //
   // Writes to EFI_SMM_SAVE_STATE_REGISTER_IO are not supported
   //
   if (Register == EFI_SMM_SAVE_STATE_REGISTER_IO) {
     return EFI_NOT_FOUND;
   }
 
   //
   // Convert Register to a register lookup table index.  Let
   // PiSmmCpuDxeSmm implement other special registers (currently
   // there is only EFI_SMM_SAVE_STATE_REGISTER_PROCESSOR_ID).
   //
   RegisterIndex = GetRegisterIndex (Register);
   if (RegisterIndex == 0) {
-    return Register < EFI_SMM_SAVE_STATE_REGISTER_IO ? EFI_NOT_FOUND : EFI_UNSUPPORTED;
+    return (Register < EFI_SMM_SAVE_STATE_REGISTER_IO ?
+            EFI_NOT_FOUND :
+            EFI_UNSUPPORTED);
   }
 
   CpuSaveState = (QEMU_SMRAM_SAVE_STATE_MAP *)gSmst->CpuSaveState[CpuIndex];
 
   //
   // Do not write non-writable SaveState, because it will cause exception.
-  // 
+  //
   if (!mSmmCpuWidthOffset[RegisterIndex].Writeable) {
     return EFI_UNSUPPORTED;
   }
 
   //
   // Check CPU mode
   //
   if ((CpuSaveState->x86.SMMRevId & 0xFFFF) == 0) {
     //
-    // If 32-bit mode width is zero, then the specified register can not be accessed
+    // If 32-bit mode width is zero, then the specified register can not be
+    // accessed
     //
     if (mSmmCpuWidthOffset[RegisterIndex].Width32 == 0) {
       return EFI_NOT_FOUND;
     }
 
     //
-    // If Width is bigger than the 32-bit mode width, then the specified register can not be accessed
+    // If Width is bigger than the 32-bit mode width, then the specified
+    // register can not be accessed
     //
     if (Width > mSmmCpuWidthOffset[RegisterIndex].Width32) {
       return EFI_INVALID_PARAMETER;
     }
     //
     // Write SMM State register
     //
     ASSERT (CpuSaveState != NULL);
-    CopyMem((UINT8 *)CpuSaveState + mSmmCpuWidthOffset[RegisterIndex].Offset32, Buffer, Width);
+    CopyMem (
+      (UINT8 *)CpuSaveState + mSmmCpuWidthOffset[RegisterIndex].Offset32,
+      Buffer,
+      Width
+      );
   } else {
     //
-    // If 64-bit mode width is zero, then the specified register can not be accessed
+    // If 64-bit mode width is zero, then the specified register can not be
+    // accessed
     //
     if (mSmmCpuWidthOffset[RegisterIndex].Width64 == 0) {
       return EFI_NOT_FOUND;
     }
 
     //
-    // If Width is bigger than the 64-bit mode width, then the specified register can not be accessed
+    // If Width is bigger than the 64-bit mode width, then the specified
+    // register can not be accessed
     //
     if (Width > mSmmCpuWidthOffset[RegisterIndex].Width64) {
       return EFI_INVALID_PARAMETER;
     }
 
     //
     // Write lower 32-bits of SMM State register
     //
-    CopyMem((UINT8 *)CpuSaveState + mSmmCpuWidthOffset[RegisterIndex].Offset64Lo, Buffer, MIN (4, Width));
+    CopyMem (
+      (UINT8 *)CpuSaveState + mSmmCpuWidthOffset[RegisterIndex].Offset64Lo,
+      Buffer,
+      MIN (4, Width)
+      );
     if (Width >= 4) {
       //
       // Write upper 32-bits of SMM State register
       //
-      CopyMem((UINT8 *)CpuSaveState + mSmmCpuWidthOffset[RegisterIndex].Offset64Hi, (UINT8 *)Buffer + 4, Width - 4);
+      CopyMem (
+        (UINT8 *)CpuSaveState + mSmmCpuWidthOffset[RegisterIndex].Offset64Hi,
+        (UINT8 *)Buffer + 4,
+        Width - 4
+        );
     }
   }
   return EFI_SUCCESS;
 }
 
 /**
   This function is hook point called after the gEfiSmmReadyToLockProtocolGuid
   notification is completely processed.
 **/
 VOID
 EFIAPI
 SmmCpuFeaturesCompleteSmmReadyToLock (
   VOID
   )
 {
 }
 
 /**
-  This API provides a method for a CPU to allocate a specific region for storing page tables.
+  This API provides a method for a CPU to allocate a specific region for
+  storing page tables.
 
   This API can be called more once to allocate memory for page tables.
 
-  Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns a pointer to the
-  allocated buffer.  The buffer returned is aligned on a 4KB boundary.  If Pages is 0, then NULL
-  is returned.  If there is not enough memory remaining to satisfy the request, then NULL is
-  returned.
+  Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns
+  a pointer to the allocated buffer.  The buffer returned is aligned on a 4KB
+  boundary.  If Pages is 0, then NULL is returned.  If there is not enough
+  memory remaining to satisfy the request, then NULL is returned.
 
-  This function can also return NULL if there is no preference on where the page tables are allocated in SMRAM.
+  This function can also return NULL if there is no preference on where the
+  page tables are allocated in SMRAM.
 
   @param  Pages                 The number of 4 KB pages to allocate.
 
   @return A pointer to the allocated buffer for page tables.
   @retval NULL      Fail to allocate a specific region for storing page tables,
-                    Or there is no preference on where the page tables are allocated in SMRAM.
+                    Or there is no preference on where the page tables are
+                    allocated in SMRAM.
 
 **/
 VOID *
 EFIAPI
 SmmCpuFeaturesAllocatePageTableMemory (
   IN UINTN           Pages
   )
 {
   return NULL;
 }
 
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 11/20] OvmfPkg/SmmCpuFeaturesLib: upper-case the "static" keyword
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (9 preceding siblings ...)
  2018-03-02  0:03 ` [PATCH 10/20] OvmfPkg/SmmCpuFeaturesLib: rewrap to 79 columns Laszlo Ersek
@ 2018-03-02  0:03 ` Laszlo Ersek
  2018-03-02  0:04 ` [PATCH 12/20] OvmfPkg/SmmCpuFeaturesLib: sort #includes, and entries in INF file sections Laszlo Ersek
                   ` (10 subsequent siblings)
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:03 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

In edk2, the "static" keyword is spelled "STATIC". Also let "STATIC" stand
alone on a line in function definitions.

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
index a876a6e34751..6b9924e49426 100644
--- a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
+++ b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
@@ -427,61 +427,61 @@ typedef struct {
 ///
 /// Structure used to build a lookup table to retrieve the widths and offsets
 /// associated with each supported EFI_SMM_SAVE_STATE_REGISTER value
 ///
 
 #define SMM_SAVE_STATE_REGISTER_FIRST_INDEX             1
 
 typedef struct {
   UINT8   Width32;
   UINT8   Width64;
   UINT16  Offset32;
   UINT16  Offset64Lo;
   UINT16  Offset64Hi;
   BOOLEAN Writeable;
 } CPU_SMM_SAVE_STATE_LOOKUP_ENTRY;
 
 ///
 /// Table used by GetRegisterIndex() to convert an EFI_SMM_SAVE_STATE_REGISTER
 /// value to an index into a table of type CPU_SMM_SAVE_STATE_LOOKUP_ENTRY
 ///
-static CONST CPU_SMM_SAVE_STATE_REGISTER_RANGE mSmmCpuRegisterRanges[] = {
+STATIC CONST CPU_SMM_SAVE_STATE_REGISTER_RANGE mSmmCpuRegisterRanges[] = {
   SMM_REGISTER_RANGE (
     EFI_SMM_SAVE_STATE_REGISTER_GDTBASE,
     EFI_SMM_SAVE_STATE_REGISTER_LDTINFO
     ),
   SMM_REGISTER_RANGE (
     EFI_SMM_SAVE_STATE_REGISTER_ES,
     EFI_SMM_SAVE_STATE_REGISTER_RIP
     ),
   SMM_REGISTER_RANGE (
     EFI_SMM_SAVE_STATE_REGISTER_RFLAGS,
     EFI_SMM_SAVE_STATE_REGISTER_CR4
     ),
   { (EFI_SMM_SAVE_STATE_REGISTER)0, (EFI_SMM_SAVE_STATE_REGISTER)0, 0 }
 };
 
 ///
 /// Lookup table used to retrieve the widths and offsets associated with each
 /// supported EFI_SMM_SAVE_STATE_REGISTER value
 ///
-static CONST CPU_SMM_SAVE_STATE_LOOKUP_ENTRY mSmmCpuWidthOffset[] = {
+STATIC CONST CPU_SMM_SAVE_STATE_LOOKUP_ENTRY mSmmCpuWidthOffset[] = {
   {
     0,                                    // Width32
     0,                                    // Width64
     0,                                    // Offset32
     0,                                    // Offset64Lo
     0,                                    // Offset64Hi
     FALSE                                 // Writeable
   }, // Reserved
 
   //
   // CPU Save State registers defined in PI SMM CPU Protocol.
   //
   {
     0,                                    // Width32
     8,                                    // Width64
     0,                                    // Offset32
     SMM_CPU_OFFSET (x64._GDTRBase),       // Offset64Lo
     SMM_CPU_OFFSET (x64._GDTRBase) + 4,   // Offset64Hi
     FALSE                                 // Writeable
   }, // EFI_SMM_SAVE_STATE_REGISTER_GDTBASE = 4
@@ -816,41 +816,42 @@ static CONST CPU_SMM_SAVE_STATE_LOOKUP_ENTRY mSmmCpuWidthOffset[] = {
     0,                                    // Offset32
     SMM_CPU_OFFSET (x64._CR4),            // Offset64Lo
     SMM_CPU_OFFSET (x64._CR4) + 4,        // Offset64Hi
     FALSE                                 // Writeable
   }, // EFI_SMM_SAVE_STATE_REGISTER_CR4 = 54
 };
 
 //
 // No support for I/O restart
 //
 
 /**
   Read information from the CPU save state.
 
   @param  Register  Specifies the CPU register to read form the save state.
 
   @retval 0   Register is not valid
   @retval >0  Index into mSmmCpuWidthOffset[] associated with Register
 
 **/
-static UINTN
+STATIC
+UINTN
 GetRegisterIndex (
   IN EFI_SMM_SAVE_STATE_REGISTER  Register
   )
 {
   UINTN  Index;
   UINTN  Offset;
 
   for (Index = 0, Offset = SMM_SAVE_STATE_REGISTER_FIRST_INDEX;
        mSmmCpuRegisterRanges[Index].Length != 0;
        Index++) {
     if (Register >= mSmmCpuRegisterRanges[Index].Start &&
         Register <= mSmmCpuRegisterRanges[Index].End) {
       return Register - mSmmCpuRegisterRanges[Index].Start + Offset;
     }
     Offset += mSmmCpuRegisterRanges[Index].Length;
   }
   return 0;
 }
 
 /**
@@ -859,41 +860,42 @@ GetRegisterIndex (
   This function abstracts the differences that whether the CPU Save State
   register is in the IA32 CPU Save State Map or X64 CPU Save State Map.
 
   This function supports reading a CPU Save State register in SMBase relocation
   handler.
 
   @param[in]  CpuIndex       Specifies the zero-based index of the CPU save
                              state.
   @param[in]  RegisterIndex  Index into mSmmCpuWidthOffset[] look up table.
   @param[in]  Width          The number of bytes to read from the CPU save
                              state.
   @param[out] Buffer         Upon return, this holds the CPU register value
                              read from the save state.
 
   @retval EFI_SUCCESS           The register was read from Save State.
   @retval EFI_NOT_FOUND         The register is not defined for the Save State
                                 of Processor.
   @retval EFI_INVALID_PARAMTER  This or Buffer is NULL.
 
 **/
-static EFI_STATUS
+STATIC
+EFI_STATUS
 ReadSaveStateRegisterByIndex (
   IN UINTN   CpuIndex,
   IN UINTN   RegisterIndex,
   IN UINTN   Width,
   OUT VOID   *Buffer
   )
 {
   QEMU_SMRAM_SAVE_STATE_MAP  *CpuSaveState;
 
   CpuSaveState = (QEMU_SMRAM_SAVE_STATE_MAP *)gSmst->CpuSaveState[CpuIndex];
 
   if ((CpuSaveState->x86.SMMRevId & 0xFFFF) == 0) {
     //
     // If 32-bit mode width is zero, then the specified register can not be
     // accessed
     //
     if (mSmmCpuWidthOffset[RegisterIndex].Width32 == 0) {
       return EFI_NOT_FOUND;
     }
 
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 12/20] OvmfPkg/SmmCpuFeaturesLib: sort #includes, and entries in INF file sections
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (10 preceding siblings ...)
  2018-03-02  0:03 ` [PATCH 11/20] OvmfPkg/SmmCpuFeaturesLib: upper-case the "static" keyword Laszlo Ersek
@ 2018-03-02  0:04 ` Laszlo Ersek
  2018-03-02  0:04 ` [PATCH 13/20] OvmfPkg/SmmCpuFeaturesLib: remove unneeded #includes and LibraryClasses Laszlo Ersek
                   ` (9 subsequent siblings)
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:04 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf | 2 +-
 OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c   | 8 ++++----
 2 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
index 75b24606b9df..9448bb166671 100644
--- a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
+++ b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
@@ -18,23 +18,23 @@ [Defines]
   INF_VERSION                    = 0x00010005
   BASE_NAME                      = SmmCpuFeaturesLib
   MODULE_UNI_FILE                = SmmCpuFeaturesLib.uni
   FILE_GUID                      = AC9991BE-D77A-464C-A8DE-A873DB8A4836
   MODULE_TYPE                    = DXE_SMM_DRIVER
   VERSION_STRING                 = 1.0
   LIBRARY_CLASS                  = SmmCpuFeaturesLib
   CONSTRUCTOR                    = SmmCpuFeaturesLibConstructor
 
 [Sources]
   SmmCpuFeaturesLib.c
 
 [Packages]
   MdePkg/MdePkg.dec
   OvmfPkg/OvmfPkg.dec
   UefiCpuPkg/UefiCpuPkg.dec
 
 [LibraryClasses]
   BaseLib
   BaseMemoryLib
-  PcdLib
   DebugLib
+  PcdLib
   SmmServicesTableLib
diff --git a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
index 6b9924e49426..75b9ce0e2b12 100644
--- a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
+++ b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
@@ -1,42 +1,42 @@
 /** @file
   The CPU specific programming for PiSmmCpuDxeSmm module.
 
   Copyright (c) 2010 - 2015, Intel Corporation. All rights reserved.<BR>
 
   This program and the accompanying materials are licensed and made available
   under the terms and conditions of the BSD License which accompanies this
   distribution.  The full text of the license may be found at
   http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT
   WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 **/
 
-#include <PiSmm.h>
-#include <Library/SmmCpuFeaturesLib.h>
 #include <Library/BaseLib.h>
 #include <Library/BaseMemoryLib.h>
-#include <Library/PcdLib.h>
+#include <Library/DebugLib.h>
 #include <Library/MemoryAllocationLib.h>
+#include <Library/PcdLib.h>
+#include <Library/SmmCpuFeaturesLib.h>
 #include <Library/SmmServicesTableLib.h>
-#include <Library/DebugLib.h>
+#include <PiSmm.h>
 #include <Register/QemuSmramSaveStateMap.h>
 
 //
 // EFER register LMA bit
 //
 #define LMA BIT10
 
 /**
   The constructor function
 
   @param[in]  ImageHandle  The firmware allocated handle for the EFI image.
   @param[in]  SystemTable  A pointer to the EFI System Table.
 
   @retval EFI_SUCCESS      The constructor always returns EFI_SUCCESS.
 
 **/
 EFI_STATUS
 EFIAPI
 SmmCpuFeaturesLibConstructor (
   IN EFI_HANDLE        ImageHandle,
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 13/20] OvmfPkg/SmmCpuFeaturesLib: remove unneeded #includes and LibraryClasses
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (11 preceding siblings ...)
  2018-03-02  0:04 ` [PATCH 12/20] OvmfPkg/SmmCpuFeaturesLib: sort #includes, and entries in INF file sections Laszlo Ersek
@ 2018-03-02  0:04 ` Laszlo Ersek
  2018-03-02  0:04 ` [PATCH 14/20] OvmfPkg/AmdSevDxe: rewrap to 79 characters width Laszlo Ersek
                   ` (8 subsequent siblings)
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:04 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf | 1 -
 OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c   | 2 --
 2 files changed, 3 deletions(-)

diff --git a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
index 9448bb166671..5184abbf21bd 100644
--- a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
+++ b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
@@ -19,22 +19,21 @@ [Defines]
   BASE_NAME                      = SmmCpuFeaturesLib
   MODULE_UNI_FILE                = SmmCpuFeaturesLib.uni
   FILE_GUID                      = AC9991BE-D77A-464C-A8DE-A873DB8A4836
   MODULE_TYPE                    = DXE_SMM_DRIVER
   VERSION_STRING                 = 1.0
   LIBRARY_CLASS                  = SmmCpuFeaturesLib
   CONSTRUCTOR                    = SmmCpuFeaturesLibConstructor
 
 [Sources]
   SmmCpuFeaturesLib.c
 
 [Packages]
   MdePkg/MdePkg.dec
   OvmfPkg/OvmfPkg.dec
   UefiCpuPkg/UefiCpuPkg.dec
 
 [LibraryClasses]
   BaseLib
   BaseMemoryLib
   DebugLib
-  PcdLib
   SmmServicesTableLib
diff --git a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
index 75b9ce0e2b12..13d929a983be 100644
--- a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
+++ b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
@@ -1,39 +1,37 @@
 /** @file
   The CPU specific programming for PiSmmCpuDxeSmm module.
 
   Copyright (c) 2010 - 2015, Intel Corporation. All rights reserved.<BR>
 
   This program and the accompanying materials are licensed and made available
   under the terms and conditions of the BSD License which accompanies this
   distribution.  The full text of the license may be found at
   http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT
   WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 **/
 
 #include <Library/BaseLib.h>
 #include <Library/BaseMemoryLib.h>
 #include <Library/DebugLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/PcdLib.h>
 #include <Library/SmmCpuFeaturesLib.h>
 #include <Library/SmmServicesTableLib.h>
 #include <PiSmm.h>
 #include <Register/QemuSmramSaveStateMap.h>
 
 //
 // EFER register LMA bit
 //
 #define LMA BIT10
 
 /**
   The constructor function
 
   @param[in]  ImageHandle  The firmware allocated handle for the EFI image.
   @param[in]  SystemTable  A pointer to the EFI System Table.
 
   @retval EFI_SUCCESS      The constructor always returns EFI_SUCCESS.
 
 **/
 EFI_STATUS
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 14/20] OvmfPkg/AmdSevDxe: rewrap to 79 characters width
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (12 preceding siblings ...)
  2018-03-02  0:04 ` [PATCH 13/20] OvmfPkg/SmmCpuFeaturesLib: remove unneeded #includes and LibraryClasses Laszlo Ersek
@ 2018-03-02  0:04 ` Laszlo Ersek
  2018-03-02  0:04 ` [PATCH 15/20] OvmfPkg/AmdSevDxe: sort #includes, and entries in INF file sections Laszlo Ersek
                   ` (7 subsequent siblings)
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:04 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

There are many overlong lines; it's hard to work with the module like
this. Rewrap all files to 79 columns.

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/AmdSevDxe/AmdSevDxe.inf | 11 +++----
 OvmfPkg/AmdSevDxe/AmdSevDxe.c   | 30 +++++++++++---------
 2 files changed, 22 insertions(+), 19 deletions(-)

diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.inf b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
index 41635a57a454..2ed778979373 100644
--- a/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
+++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
@@ -1,33 +1,34 @@
 #/** @file
 #
 #  Driver clears the encryption attribute from MMIO regions when SEV is enabled
 #
 #  Copyright (c) 2017, AMD Inc. All rights reserved.<BR>
 #
-#  This program and the accompanying materials
-#  are licensed and made available under the terms and conditions of the BSD
-#  License which accompanies this distribution.  The full text of the license may
-#  be found at http://opensource.org/licenses/bsd-license.php
+#  This program and the accompanying materials are licensed and made available
+#  under the terms and conditions of the BSD License which accompanies this
+#  distribution.  The full text of the license may be found at
+#  http://opensource.org/licenses/bsd-license.php
 #
 #  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-#  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR
+#  IMPLIED.
 #
 #**/
 
 [Defines]
   INF_VERSION                    = 1.25
   BASE_NAME                      = AmdSevDxe
   FILE_GUID                      = 2ec9da37-ee35-4de9-86c5-6d9a81dc38a7
   MODULE_TYPE                    = DXE_DRIVER
   VERSION_STRING                 = 1.0
   ENTRY_POINT                    = AmdSevDxeEntryPoint
 
 [Sources]
   AmdSevDxe.c
 
 [Packages]
   MdePkg/MdePkg.dec
   MdeModulePkg/MdeModulePkg.dec
   OvmfPkg/OvmfPkg.dec
 
 [LibraryClasses]
diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.c b/OvmfPkg/AmdSevDxe/AmdSevDxe.c
index e472096320ea..065d7381b35b 100644
--- a/OvmfPkg/AmdSevDxe/AmdSevDxe.c
+++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.c
@@ -1,75 +1,77 @@
 /** @file
 
   AMD Sev Dxe driver. This driver is dispatched early in DXE, due to being list
-  in APRIORI. It clears C-bit from MMIO and NonExistent Memory space when SEV is
-  enabled.
+  in APRIORI. It clears C-bit from MMIO and NonExistent Memory space when SEV
+  is enabled.
 
   Copyright (c) 2017, AMD Inc. All rights reserved.<BR>
 
-  This program and the accompanying materials
-  are licensed and made available under the terms and conditions of the BSD
-  License which accompanies this distribution.  The full text of the license may
-  be found at http://opensource.org/licenses/bsd-license.php
+  This program and the accompanying materials are licensed and made available
+  under the terms and conditions of the BSD License which accompanies this
+  distribution.  The full text of the license may be found at
+  http://opensource.org/licenses/bsd-license.php
 
-  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT
+  WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
 **/
 
 #include <PiDxe.h>
 
 #include <Library/BaseLib.h>
 #include <Library/DebugLib.h>
 #include <Library/BaseMemoryLib.h>
 #include <Library/MemoryAllocationLib.h>
 #include <Library/UefiBootServicesTableLib.h>
 #include <Library/DxeServicesTableLib.h>
 #include <Library/MemEncryptSevLib.h>
 
 EFI_STATUS
 EFIAPI
 AmdSevDxeEntryPoint (
   IN EFI_HANDLE         ImageHandle,
   IN EFI_SYSTEM_TABLE   *SystemTable
   )
 {
   EFI_STATUS                       Status;
   EFI_GCD_MEMORY_SPACE_DESCRIPTOR  *AllDescMap;
   UINTN                            NumEntries;
   UINTN                            Index;
 
   //
   // Do nothing when SEV is not enabled
   //
   if (!MemEncryptSevIsEnabled ()) {
     return EFI_UNSUPPORTED;
   }
 
   //
   // Iterate through the GCD map and clear the C-bit from MMIO and NonExistent
-  // memory space. The NonExistent memory space will be used for mapping the MMIO
-  // space added later (eg PciRootBridge). By clearing both known MMIO and
+  // memory space. The NonExistent memory space will be used for mapping the
+  // MMIO space added later (eg PciRootBridge). By clearing both known MMIO and
   // NonExistent memory space can gurantee that current and furture MMIO adds
   // will have C-bit cleared.
   //
   Status = gDS->GetMemorySpaceMap (&NumEntries, &AllDescMap);
   if (!EFI_ERROR (Status)) {
     for (Index = 0; Index < NumEntries; Index++) {
       CONST EFI_GCD_MEMORY_SPACE_DESCRIPTOR *Desc;
 
       Desc = &AllDescMap[Index];
       if (Desc->GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo ||
           Desc->GcdMemoryType == EfiGcdMemoryTypeNonExistent) {
-        Status = MemEncryptSevClearPageEncMask (0,
-                                                Desc->BaseAddress,
-                                                EFI_SIZE_TO_PAGES(Desc->Length),
-                                                FALSE);
+        Status = MemEncryptSevClearPageEncMask (
+                   0,
+                   Desc->BaseAddress,
+                   EFI_SIZE_TO_PAGES (Desc->Length),
+                   FALSE
+                   );
         ASSERT_EFI_ERROR (Status);
       }
     }
 
     FreePool (AllDescMap);
   }
 
   return EFI_SUCCESS;
 }
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 15/20] OvmfPkg/AmdSevDxe: sort #includes, and entries in INF file sections
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (13 preceding siblings ...)
  2018-03-02  0:04 ` [PATCH 14/20] OvmfPkg/AmdSevDxe: rewrap to 79 characters width Laszlo Ersek
@ 2018-03-02  0:04 ` Laszlo Ersek
  2018-03-02  0:04 ` [PATCH 16/20] OvmfPkg/AmdSevDxe: refresh #includes and LibraryClasses Laszlo Ersek
                   ` (6 subsequent siblings)
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:04 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/AmdSevDxe/AmdSevDxe.inf | 10 +++++-----
 OvmfPkg/AmdSevDxe/AmdSevDxe.c   |  9 ++++-----
 2 files changed, 9 insertions(+), 10 deletions(-)

diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.inf b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
index 2ed778979373..d4a0a2635d2e 100644
--- a/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
+++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
@@ -10,35 +10,35 @@
 #  http://opensource.org/licenses/bsd-license.php
 #
 #  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
 #  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR
 #  IMPLIED.
 #
 #**/
 
 [Defines]
   INF_VERSION                    = 1.25
   BASE_NAME                      = AmdSevDxe
   FILE_GUID                      = 2ec9da37-ee35-4de9-86c5-6d9a81dc38a7
   MODULE_TYPE                    = DXE_DRIVER
   VERSION_STRING                 = 1.0
   ENTRY_POINT                    = AmdSevDxeEntryPoint
 
 [Sources]
   AmdSevDxe.c
 
 [Packages]
-  MdePkg/MdePkg.dec
   MdeModulePkg/MdeModulePkg.dec
+  MdePkg/MdePkg.dec
   OvmfPkg/OvmfPkg.dec
 
 [LibraryClasses]
   BaseLib
-  UefiLib
-  UefiDriverEntryPoint
-  UefiBootServicesTableLib
-  DxeServicesTableLib
   DebugLib
+  DxeServicesTableLib
   MemEncryptSevLib
+  UefiBootServicesTableLib
+  UefiDriverEntryPoint
+  UefiLib
 
 [Depex]
   TRUE
diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.c b/OvmfPkg/AmdSevDxe/AmdSevDxe.c
index 065d7381b35b..9ac13acb8b22 100644
--- a/OvmfPkg/AmdSevDxe/AmdSevDxe.c
+++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.c
@@ -1,47 +1,46 @@
 /** @file
 
   AMD Sev Dxe driver. This driver is dispatched early in DXE, due to being list
   in APRIORI. It clears C-bit from MMIO and NonExistent Memory space when SEV
   is enabled.
 
   Copyright (c) 2017, AMD Inc. All rights reserved.<BR>
 
   This program and the accompanying materials are licensed and made available
   under the terms and conditions of the BSD License which accompanies this
   distribution.  The full text of the license may be found at
   http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT
   WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
 **/
 
-#include <PiDxe.h>
-
 #include <Library/BaseLib.h>
-#include <Library/DebugLib.h>
 #include <Library/BaseMemoryLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/UefiBootServicesTableLib.h>
+#include <Library/DebugLib.h>
 #include <Library/DxeServicesTableLib.h>
 #include <Library/MemEncryptSevLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <PiDxe.h>
 
 EFI_STATUS
 EFIAPI
 AmdSevDxeEntryPoint (
   IN EFI_HANDLE         ImageHandle,
   IN EFI_SYSTEM_TABLE   *SystemTable
   )
 {
   EFI_STATUS                       Status;
   EFI_GCD_MEMORY_SPACE_DESCRIPTOR  *AllDescMap;
   UINTN                            NumEntries;
   UINTN                            Index;
 
   //
   // Do nothing when SEV is not enabled
   //
   if (!MemEncryptSevIsEnabled ()) {
     return EFI_UNSUPPORTED;
   }
 
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 16/20] OvmfPkg/AmdSevDxe: refresh #includes and LibraryClasses
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (14 preceding siblings ...)
  2018-03-02  0:04 ` [PATCH 15/20] OvmfPkg/AmdSevDxe: sort #includes, and entries in INF file sections Laszlo Ersek
@ 2018-03-02  0:04 ` Laszlo Ersek
  2018-03-02  0:04 ` [PATCH 17/20] OvmfPkg/MemEncryptSevLib: find pages of initial SMRAM save state map Laszlo Ersek
                   ` (5 subsequent siblings)
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:04 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

List those and only those libraries that are used.

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/AmdSevDxe/AmdSevDxe.inf | 4 +---
 OvmfPkg/AmdSevDxe/AmdSevDxe.c   | 4 ----
 2 files changed, 1 insertion(+), 7 deletions(-)

diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.inf b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
index d4a0a2635d2e..3aff7e292053 100644
--- a/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
+++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
@@ -15,30 +15,28 @@
 #
 #**/
 
 [Defines]
   INF_VERSION                    = 1.25
   BASE_NAME                      = AmdSevDxe
   FILE_GUID                      = 2ec9da37-ee35-4de9-86c5-6d9a81dc38a7
   MODULE_TYPE                    = DXE_DRIVER
   VERSION_STRING                 = 1.0
   ENTRY_POINT                    = AmdSevDxeEntryPoint
 
 [Sources]
   AmdSevDxe.c
 
 [Packages]
   MdeModulePkg/MdeModulePkg.dec
   MdePkg/MdePkg.dec
   OvmfPkg/OvmfPkg.dec
 
 [LibraryClasses]
-  BaseLib
   DebugLib
   DxeServicesTableLib
   MemEncryptSevLib
-  UefiBootServicesTableLib
+  MemoryAllocationLib
   UefiDriverEntryPoint
-  UefiLib
 
 [Depex]
   TRUE
diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.c b/OvmfPkg/AmdSevDxe/AmdSevDxe.c
index 9ac13acb8b22..8f02d0627e02 100644
--- a/OvmfPkg/AmdSevDxe/AmdSevDxe.c
+++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.c
@@ -1,46 +1,42 @@
 /** @file
 
   AMD Sev Dxe driver. This driver is dispatched early in DXE, due to being list
   in APRIORI. It clears C-bit from MMIO and NonExistent Memory space when SEV
   is enabled.
 
   Copyright (c) 2017, AMD Inc. All rights reserved.<BR>
 
   This program and the accompanying materials are licensed and made available
   under the terms and conditions of the BSD License which accompanies this
   distribution.  The full text of the license may be found at
   http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT
   WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
 **/
 
-#include <Library/BaseLib.h>
-#include <Library/BaseMemoryLib.h>
 #include <Library/DebugLib.h>
 #include <Library/DxeServicesTableLib.h>
 #include <Library/MemEncryptSevLib.h>
 #include <Library/MemoryAllocationLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <PiDxe.h>
 
 EFI_STATUS
 EFIAPI
 AmdSevDxeEntryPoint (
   IN EFI_HANDLE         ImageHandle,
   IN EFI_SYSTEM_TABLE   *SystemTable
   )
 {
   EFI_STATUS                       Status;
   EFI_GCD_MEMORY_SPACE_DESCRIPTOR  *AllDescMap;
   UINTN                            NumEntries;
   UINTN                            Index;
 
   //
   // Do nothing when SEV is not enabled
   //
   if (!MemEncryptSevIsEnabled ()) {
     return EFI_UNSUPPORTED;
   }
 
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 17/20] OvmfPkg/MemEncryptSevLib: find pages of initial SMRAM save state map
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (15 preceding siblings ...)
  2018-03-02  0:04 ` [PATCH 16/20] OvmfPkg/AmdSevDxe: refresh #includes and LibraryClasses Laszlo Ersek
@ 2018-03-02  0:04 ` Laszlo Ersek
  2018-03-02  0:04 ` [PATCH 18/20] OvmfPkg/PlatformPei: SEV: allocate " Laszlo Ersek
                   ` (4 subsequent siblings)
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:04 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

In the next three patches, we're going to modify three modules under
OvmfPkg. When OVMF is built with -D SMM_REQUIRE and runs in an SEV guest,
each affected module will have to know the page range that covers the
initial (pre-SMBASE relocation) SMRAM save state map. Add a helper
function to MemEncryptSevLib that calculates the "base address" and
"number of pages" constants for this page range.

(In a RELEASE build -- i.e., with assertions disabled and optimization
enabled --, the helper function can be compiled to store two constants
determined at compile time.)

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf   |  4 ++
 OvmfPkg/Include/Library/MemEncryptSevLib.h                      | 23 +++++++++
 OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c | 51 ++++++++++++++++++++
 3 files changed, 78 insertions(+)

diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf b/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
index 2f0a2392a7ad..464fe1f33e66 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
@@ -34,20 +34,24 @@ [Packages]
   MdeModulePkg/MdeModulePkg.dec
   MdePkg/MdePkg.dec
   OvmfPkg/OvmfPkg.dec
   UefiCpuPkg/UefiCpuPkg.dec
 
 [Sources.X64]
   MemEncryptSevLibInternal.c
   X64/MemEncryptSevLib.c
   X64/VirtualMemory.c
 
 [Sources.IA32]
   Ia32/MemEncryptSevLib.c
   MemEncryptSevLibInternal.c
 
 [LibraryClasses]
   BaseLib
   CacheMaintenanceLib
   CpuLib
   DebugLib
   MemoryAllocationLib
+  PcdLib
+
+[FeaturePcd]
+  gUefiOvmfPkgTokenSpaceGuid.PcdSmmSmramRequire
diff --git a/OvmfPkg/Include/Library/MemEncryptSevLib.h b/OvmfPkg/Include/Library/MemEncryptSevLib.h
index e5ebb4401818..1e2ec8641d46 100644
--- a/OvmfPkg/Include/Library/MemEncryptSevLib.h
+++ b/OvmfPkg/Include/Library/MemEncryptSevLib.h
@@ -69,21 +69,44 @@ MemEncryptSevClearPageEncMask (
                                       address of a memory region.
   @param[in]  NumPages                The number of pages from start memory
                                       region.
   @param[in]  Flush                   Flush the caches before setting the bit
                                       (mostly TRUE except MMIO addresses)
 
   @retval RETURN_SUCCESS              The attributes were set for the memory
                                       region.
   @retval RETURN_INVALID_PARAMETER    Number of pages is zero.
   @retval RETURN_UNSUPPORTED          Setting the memory encryption attribute
                                       is not supported
 **/
 RETURN_STATUS
 EFIAPI
 MemEncryptSevSetPageEncMask (
   IN PHYSICAL_ADDRESS         Cr3BaseAddress,
   IN PHYSICAL_ADDRESS         BaseAddress,
   IN UINTN                    NumPages,
   IN BOOLEAN                  Flush
   );
+
+
+/**
+  Locate the page range that covers the initial (pre-SMBASE-relocation) SMRAM
+  Save State Map.
+
+  @param[out] BaseAddress     The base address of the lowest-address page that
+                              covers the initial SMRAM Save State Map.
+
+  @param[out] NumberOfPages   The number of pages in the page range that covers
+                              the initial SMRAM Save State Map.
+
+  @retval RETURN_SUCCESS      BaseAddress and NumberOfPages have been set on
+                              output.
+
+  @retval RETURN_UNSUPPORTED  SMM is unavailable.
+**/
+RETURN_STATUS
+EFIAPI
+MemEncryptSevLocateInitialSmramSaveStateMapPages (
+  OUT UINTN *BaseAddress,
+  OUT UINTN *NumberOfPages
+  );
 #endif // _MEM_ENCRYPT_SEV_LIB_H_
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c b/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c
index 7078ab0d3f46..b92ba50c616c 100644
--- a/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c
@@ -1,42 +1,46 @@
 /** @file
 
   Secure Encrypted Virtualization (SEV) library helper function
 
   Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
 
   This program and the accompanying materials are licensed and made available
   under the terms and conditions of the BSD License which accompanies this
   distribution.  The full text of the license may be found at
   http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
   WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
 **/
 
 #include <Library/BaseLib.h>
 #include <Library/DebugLib.h>
 #include <Library/MemEncryptSevLib.h>
+#include <Library/PcdLib.h>
 #include <Register/Amd/Cpuid.h>
 #include <Register/Amd/Msr.h>
 #include <Register/Cpuid.h>
+#include <Register/QemuSmramSaveStateMap.h>
+#include <Register/SmramSaveStateMap.h>
+#include <Uefi/UefiBaseType.h>
 
 STATIC BOOLEAN mSevStatus = FALSE;
 STATIC BOOLEAN mSevStatusChecked = FALSE;
 
 /**
 
   Returns a boolean to indicate whether SEV is enabled
 
   @retval TRUE           SEV is enabled
   @retval FALSE          SEV is not enabled
   **/
 STATIC
 BOOLEAN
 EFIAPI
 InternalMemEncryptSevIsEnabled (
   VOID
   )
 {
   UINT32                            RegEax;
   MSR_SEV_STATUS_REGISTER           Msr;
@@ -70,20 +74,67 @@ InternalMemEncryptSevIsEnabled (
   Returns a boolean to indicate whether SEV is enabled
 
   @retval TRUE           SEV is enabled
   @retval FALSE          SEV is not enabled
 **/
 BOOLEAN
 EFIAPI
 MemEncryptSevIsEnabled (
   VOID
   )
 {
   if (mSevStatusChecked) {
     return mSevStatus;
   }
 
   mSevStatus = InternalMemEncryptSevIsEnabled();
   mSevStatusChecked = TRUE;
 
   return mSevStatus;
 }
+
+
+/**
+  Locate the page range that covers the initial (pre-SMBASE-relocation) SMRAM
+  Save State Map.
+
+  @param[out] BaseAddress     The base address of the lowest-address page that
+                              covers the initial SMRAM Save State Map.
+
+  @param[out] NumberOfPages   The number of pages in the page range that covers
+                              the initial SMRAM Save State Map.
+
+  @retval RETURN_SUCCESS      BaseAddress and NumberOfPages have been set on
+                              output.
+
+  @retval RETURN_UNSUPPORTED  SMM is unavailable.
+**/
+RETURN_STATUS
+EFIAPI
+MemEncryptSevLocateInitialSmramSaveStateMapPages (
+  OUT UINTN *BaseAddress,
+  OUT UINTN *NumberOfPages
+  )
+{
+  UINTN MapStart;
+  UINTN MapEnd;
+  UINTN MapPagesStart; // MapStart rounded down to page boundary
+  UINTN MapPagesEnd;   // MapEnd rounded up to page boundary
+  UINTN MapPagesSize;  // difference between MapPagesStart and MapPagesEnd
+
+  if (!FeaturePcdGet (PcdSmmSmramRequire)) {
+    return RETURN_UNSUPPORTED;
+  }
+
+  MapStart      = SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET;
+  MapEnd        = MapStart + sizeof (QEMU_SMRAM_SAVE_STATE_MAP);
+  MapPagesStart = MapStart & ~(UINTN)EFI_PAGE_MASK;
+  MapPagesEnd   = ALIGN_VALUE (MapEnd, EFI_PAGE_SIZE);
+  MapPagesSize  = MapPagesEnd - MapPagesStart;
+
+  ASSERT ((MapPagesSize & EFI_PAGE_MASK) == 0);
+
+  *BaseAddress   = MapPagesStart;
+  *NumberOfPages = MapPagesSize >> EFI_PAGE_SHIFT;
+
+  return RETURN_SUCCESS;
+}
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 18/20] OvmfPkg/PlatformPei: SEV: allocate pages of initial SMRAM save state map
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (16 preceding siblings ...)
  2018-03-02  0:04 ` [PATCH 17/20] OvmfPkg/MemEncryptSevLib: find pages of initial SMRAM save state map Laszlo Ersek
@ 2018-03-02  0:04 ` Laszlo Ersek
  2018-03-02  0:04 ` [PATCH 19/20] OvmfPkg/SmmCpuFeaturesLib: SEV: encrypt+free pages of init. " Laszlo Ersek
                   ` (3 subsequent siblings)
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:04 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

In the next two patches, we'll temporarily decrypt the pages containing
the initial SMRAM save state map, for SMBASE relocation. (Unlike the
separate, relocated SMRAM save state map of each VCPU, the original,
shared map behaves similarly to a "common buffer" between guest and host.)
The decryption will occur near the beginning of the DXE phase, in
AmdSevDxe, and the re-encryption will occur in PiSmmCpuDxeSmm, via OVMF's
SmmCpuFeaturesLib instance.

There is a non-trivial time gap between these two points, and the DXE
phase might use the pages overlapping the initial SMRAM save state map for
arbitrary purposes meanwhile. In order to prevent any information leak
towards the hypervisor, make sure the DXE phase puts nothing in those
pages until re-encryption is done.

Creating a memalloc HOB for the area in question is safe:

- the temporary SEC/PEI RAM (stack and heap) is based at
  PcdOvmfSecPeiTempRamBase, which is above 8MB,

- the permanent PEI RAM (installed in PlatformPei's PublishPeiMemory()
  function) never starts below PcdOvmfDxeMemFvBase, which is also above
  8MB.

The allocated pages can be released to the DXE phase after SMBASE
relocation and re-encryption are complete.

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/PlatformPei/AmdSev.c | 29 ++++++++++++++++++++
 1 file changed, 29 insertions(+)

diff --git a/OvmfPkg/PlatformPei/AmdSev.c b/OvmfPkg/PlatformPei/AmdSev.c
index 1509f260fb0b..2e14eaf8c3cc 100644
--- a/OvmfPkg/PlatformPei/AmdSev.c
+++ b/OvmfPkg/PlatformPei/AmdSev.c
@@ -1,38 +1,39 @@
 /**@file
   Initialize Secure Encrypted Virtualization (SEV) support
 
   Copyright (c) 2017, Advanced Micro Devices. All rights reserved.<BR>
 
   This program and the accompanying materials
   are licensed and made available under the terms and conditions of the BSD
   License which accompanies this distribution.  The full text of the license
   may be found at http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
   WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
 **/
 //
 // The package level header files this module uses
 //
 #include <Library/DebugLib.h>
+#include <Library/HobLib.h>
 #include <Library/MemEncryptSevLib.h>
 #include <Library/PcdLib.h>
 #include <PiPei.h>
 #include <Register/Amd/Cpuid.h>
 #include <Register/Cpuid.h>
 
 #include "Platform.h"
 
 /**
 
   Function checks if SEV support is available, if present then it sets
   the dynamic PcdPteMemoryEncryptionAddressOrMask with memory encryption mask.
 
   **/
 VOID
 AmdSevInitialize (
   VOID
   )
 {
   CPUID_MEMORY_ENCRYPTION_INFO_EBX  Ebx;
@@ -49,21 +50,49 @@ AmdSevInitialize (
   //
   // CPUID Fn8000_001F[EBX] Bit 0:5 (memory encryption bit position)
   //
   AsmCpuid (CPUID_MEMORY_ENCRYPTION_INFO, NULL, &Ebx.Uint32, NULL, NULL);
   EncryptionMask = LShiftU64 (1, Ebx.Bits.PtePosBits);
 
   //
   // Set Memory Encryption Mask PCD
   //
   PcdStatus = PcdSet64S (PcdPteMemoryEncryptionAddressOrMask, EncryptionMask);
   ASSERT_RETURN_ERROR (PcdStatus);
 
   DEBUG ((DEBUG_INFO, "SEV is enabled (mask 0x%lx)\n", EncryptionMask));
 
   //
   // Set Pcd to Deny the execution of option ROM when security
   // violation.
   //
   PcdStatus = PcdSet32S (PcdOptionRomImageVerificationPolicy, 0x4);
   ASSERT_RETURN_ERROR (PcdStatus);
+
+  //
+  // When SMM is required, cover the pages containing the initial SMRAM Save
+  // State Map with a memory allocation HOB:
+  //
+  // There's going to be a time interval between our decrypting those pages for
+  // SMBASE relocation and re-encrypting the same pages after SMBASE
+  // relocation. We shall ensure that the DXE phase stay away from those pages
+  // until after re-encryption, in order to prevent an information leak to the
+  // hypervisor.
+  //
+  if (FeaturePcdGet (PcdSmmSmramRequire) && (mBootMode != BOOT_ON_S3_RESUME)) {
+    RETURN_STATUS LocateMapStatus;
+    UINTN         MapPagesBase;
+    UINTN         MapPagesCount;
+
+    LocateMapStatus = MemEncryptSevLocateInitialSmramSaveStateMapPages (
+                        &MapPagesBase,
+                        &MapPagesCount
+                        );
+    ASSERT_RETURN_ERROR (LocateMapStatus);
+
+    BuildMemoryAllocationHob (
+      MapPagesBase,                      // BaseAddress
+      EFI_PAGES_TO_SIZE (MapPagesCount), // Length
+      EfiBootServicesData                // MemoryType
+      );
+  }
 }
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 19/20] OvmfPkg/SmmCpuFeaturesLib: SEV: encrypt+free pages of init. save state map
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (17 preceding siblings ...)
  2018-03-02  0:04 ` [PATCH 18/20] OvmfPkg/PlatformPei: SEV: allocate " Laszlo Ersek
@ 2018-03-02  0:04 ` Laszlo Ersek
  2018-03-02  0:04 ` [PATCH 20/20] OvmfPkg/AmdSevDxe: decrypt the pages of the initial SMRAM " Laszlo Ersek
                   ` (2 subsequent siblings)
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:04 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

Based on the following patch from Brijesh Singh <brijesh.singh@amd.com>:

  [PATCH v2 1/2] OvmfPkg/AmdSevDxe: Clear the C-bit from SMM Saved State
  http://mid.mail-archive.com/20180228161415.28723-2-brijesh.singh@amd.com
  https://lists.01.org/pipermail/edk2-devel/2018-February/022016.html

Once PiSmmCpuDxeSmm relocates SMBASE for all VCPUs, the pages of the
initial SMRAM save state map can be re-encrypted (including zeroing them
out after setting the C-bit on them), and they can be released to DXE for
general use (undoing the allocation that we did in PlatformPei's
AmdSevInitialize() function).

The decryption of the same pages (which will occur chronologically
earlier) is implemented in the next patch; hence the "re-encryption" part
of this patch is currently a no-op. The series is structured like this in
order to be bisection-friendly. If the decryption patch preceded this
patch, then an info leak would be created while standing between the
patches.

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf |  2 ++
 OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c   | 38 ++++++++++++++++++++
 2 files changed, 40 insertions(+)

diff --git a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
index 5184abbf21bd..7c2aaa890b5e 100644
--- a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
+++ b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
@@ -19,21 +19,23 @@ [Defines]
   BASE_NAME                      = SmmCpuFeaturesLib
   MODULE_UNI_FILE                = SmmCpuFeaturesLib.uni
   FILE_GUID                      = AC9991BE-D77A-464C-A8DE-A873DB8A4836
   MODULE_TYPE                    = DXE_SMM_DRIVER
   VERSION_STRING                 = 1.0
   LIBRARY_CLASS                  = SmmCpuFeaturesLib
   CONSTRUCTOR                    = SmmCpuFeaturesLibConstructor
 
 [Sources]
   SmmCpuFeaturesLib.c
 
 [Packages]
   MdePkg/MdePkg.dec
   OvmfPkg/OvmfPkg.dec
   UefiCpuPkg/UefiCpuPkg.dec
 
 [LibraryClasses]
   BaseLib
   BaseMemoryLib
   DebugLib
+  MemEncryptSevLib
   SmmServicesTableLib
+  UefiBootServicesTableLib
diff --git a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
index 13d929a983be..59c319e01bfb 100644
--- a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
+++ b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
@@ -1,39 +1,41 @@
 /** @file
   The CPU specific programming for PiSmmCpuDxeSmm module.
 
   Copyright (c) 2010 - 2015, Intel Corporation. All rights reserved.<BR>
 
   This program and the accompanying materials are licensed and made available
   under the terms and conditions of the BSD License which accompanies this
   distribution.  The full text of the license may be found at
   http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT
   WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 **/
 
 #include <Library/BaseLib.h>
 #include <Library/BaseMemoryLib.h>
 #include <Library/DebugLib.h>
+#include <Library/MemEncryptSevLib.h>
 #include <Library/SmmCpuFeaturesLib.h>
 #include <Library/SmmServicesTableLib.h>
+#include <Library/UefiBootServicesTableLib.h>
 #include <PiSmm.h>
 #include <Register/QemuSmramSaveStateMap.h>
 
 //
 // EFER register LMA bit
 //
 #define LMA BIT10
 
 /**
   The constructor function
 
   @param[in]  ImageHandle  The firmware allocated handle for the EFI image.
   @param[in]  SystemTable  A pointer to the EFI System Table.
 
   @retval EFI_SUCCESS      The constructor always returns EFI_SUCCESS.
 
 **/
 EFI_STATUS
 EFIAPI
 SmmCpuFeaturesLibConstructor (
@@ -168,40 +170,76 @@ SmmCpuFeaturesHookReturnFromSmm (
     if ((CpuSaveState->x64.AutoHALTRestart & BIT0) != 0) {
       CpuSaveState->x64.AutoHALTRestart &= ~BIT0;
     }
   }
   return OriginalInstructionPointer;
 }
 
 /**
   Hook point in normal execution mode that allows the one CPU that was elected
   as monarch during System Management Mode initialization to perform additional
   initialization actions immediately after all of the CPUs have processed their
   first SMI and called SmmCpuFeaturesInitializeProcessor() relocating SMBASE
   into a buffer in SMRAM and called SmmCpuFeaturesHookReturnFromSmm().
 **/
 VOID
 EFIAPI
 SmmCpuFeaturesSmmRelocationComplete (
   VOID
   )
 {
+  EFI_STATUS Status;
+  UINTN      MapPagesBase;
+  UINTN      MapPagesCount;
+
+  if (!MemEncryptSevIsEnabled ()) {
+    return;
+  }
+
+  //
+  // Now that SMBASE relocation is complete, re-encrypt the original SMRAM save
+  // state map's container pages, and release the pages to DXE. (The pages were
+  // allocated in PlatformPei.)
+  //
+  Status = MemEncryptSevLocateInitialSmramSaveStateMapPages (
+             &MapPagesBase,
+             &MapPagesCount
+             );
+  ASSERT_EFI_ERROR (Status);
+
+  Status = MemEncryptSevSetPageEncMask (
+             0,             // Cr3BaseAddress -- use current CR3
+             MapPagesBase,  // BaseAddress
+             MapPagesCount, // NumPages
+             TRUE           // Flush
+             );
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_ERROR, "%a: MemEncryptSevSetPageEncMask(): %r\n",
+      __FUNCTION__, Status));
+    ASSERT (FALSE);
+    CpuDeadLoop ();
+  }
+
+  ZeroMem ((VOID *)MapPagesBase, EFI_PAGES_TO_SIZE (MapPagesCount));
+
+  Status = gBS->FreePages (MapPagesBase, MapPagesCount);
+  ASSERT_EFI_ERROR (Status);
 }
 
 /**
   Return the size, in bytes, of a custom SMI Handler in bytes.  If 0 is
   returned, then a custom SMI handler is not provided by this library,
   and the default SMI handler must be used.
 
   @retval 0    Use the default SMI handler.
   @retval > 0  Use the SMI handler installed by
                SmmCpuFeaturesInstallSmiHandler(). The caller is required to
                allocate enough SMRAM for each CPU to support the size of the
                custom SMI handler.
 **/
 UINTN
 EFIAPI
 SmmCpuFeaturesGetSmiHandlerSize (
   VOID
   )
 {
   return 0;
-- 
2.14.1.3.gb7cf6e02401b




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

* [PATCH 20/20] OvmfPkg/AmdSevDxe: decrypt the pages of the initial SMRAM save state map
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (18 preceding siblings ...)
  2018-03-02  0:04 ` [PATCH 19/20] OvmfPkg/SmmCpuFeaturesLib: SEV: encrypt+free pages of init. " Laszlo Ersek
@ 2018-03-02  0:04 ` Laszlo Ersek
  2018-03-02  1:16 ` [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Brijesh Singh
  2018-03-02 15:21 ` Brijesh Singh
  21 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02  0:04 UTC (permalink / raw)
  To: edk2-devel-01; +Cc: Ard Biesheuvel, Brijesh Singh, Jordan Justen

Based on the following patch from Brijesh Singh <brijesh.singh@amd.com>:

  [PATCH v2 1/2] OvmfPkg/AmdSevDxe: Clear the C-bit from SMM Saved State
  http://mid.mail-archive.com/20180228161415.28723-2-brijesh.singh@amd.com
  https://lists.01.org/pipermail/edk2-devel/2018-February/022016.html

Original commit message from Brijesh:

> When OVMF is built with SMM, SMMSaved State area (SMM_DEFAULT_SMBASE +
> SMRAM_SAVE_STATE_MAP_OFFSET) contains data which need to be accessed by
> both guest and hypervisor. Since the data need to be accessed by both
> hence we must map the SMMSaved State area as unencrypted (i.e C-bit
> cleared).
>
> This patch clears the SavedStateArea address before SMBASE relocation.
> Currently, we do not clear the SavedStateArea address after SMBASE is
> relocated due to the following reasons:
>
> 1) Guest BIOS never access the relocated SavedStateArea.
>
> 2) The C-bit works on page-aligned address, but the SavedStateArea
> address is not a page-aligned. Theoretically, we could roundup the
> address and clear the C-bit of aligned address but looking carefully we
> found that some portion of the page contains code -- which will causes a
> bigger issue for the SEV guest. When SEV is enabled, all the code must
> be encrypted otherwise hardware will cause trap.

Changes by Laszlo:

- separate AmdSevDxe bits from SmmCpuFeaturesLib bits;

- spell out PcdLib dependency with #include and in LibraryClasses;

- replace (SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET) calculation
  with call to new MemEncryptSevLocateInitialSmramSaveStateMapPages()
  function;

- consequently, pass page-aligned BaseAddress to
  MemEncryptSevClearPageEncMask();

- zero the pages before clearing the C-bit;

- pass Flush=TRUE to MemEncryptSevClearPageEncMask();

- harden the treatment of MemEncryptSevClearPageEncMask() failure.

Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
---
 OvmfPkg/AmdSevDxe/AmdSevDxe.inf |  6 +++
 OvmfPkg/AmdSevDxe/AmdSevDxe.c   | 53 ++++++++++++++++++++
 2 files changed, 59 insertions(+)

diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.inf b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
index 3aff7e292053..b7e7da002d5e 100644
--- a/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
+++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
@@ -15,28 +15,34 @@
 #
 #**/
 
 [Defines]
   INF_VERSION                    = 1.25
   BASE_NAME                      = AmdSevDxe
   FILE_GUID                      = 2ec9da37-ee35-4de9-86c5-6d9a81dc38a7
   MODULE_TYPE                    = DXE_DRIVER
   VERSION_STRING                 = 1.0
   ENTRY_POINT                    = AmdSevDxeEntryPoint
 
 [Sources]
   AmdSevDxe.c
 
 [Packages]
   MdeModulePkg/MdeModulePkg.dec
   MdePkg/MdePkg.dec
   OvmfPkg/OvmfPkg.dec
 
 [LibraryClasses]
+  BaseLib
+  BaseMemoryLib
   DebugLib
   DxeServicesTableLib
   MemEncryptSevLib
   MemoryAllocationLib
+  PcdLib
   UefiDriverEntryPoint
 
 [Depex]
   TRUE
+
+[FeaturePcd]
+  gUefiOvmfPkgTokenSpaceGuid.PcdSmmSmramRequire
diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.c b/OvmfPkg/AmdSevDxe/AmdSevDxe.c
index 8f02d0627e02..c697580ad5b8 100644
--- a/OvmfPkg/AmdSevDxe/AmdSevDxe.c
+++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.c
@@ -1,42 +1,45 @@
 /** @file
 
   AMD Sev Dxe driver. This driver is dispatched early in DXE, due to being list
   in APRIORI. It clears C-bit from MMIO and NonExistent Memory space when SEV
   is enabled.
 
   Copyright (c) 2017, AMD Inc. All rights reserved.<BR>
 
   This program and the accompanying materials are licensed and made available
   under the terms and conditions of the BSD License which accompanies this
   distribution.  The full text of the license may be found at
   http://opensource.org/licenses/bsd-license.php
 
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT
   WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
 **/
 
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
 #include <Library/DebugLib.h>
 #include <Library/DxeServicesTableLib.h>
 #include <Library/MemEncryptSevLib.h>
 #include <Library/MemoryAllocationLib.h>
+#include <Library/PcdLib.h>
 
 EFI_STATUS
 EFIAPI
 AmdSevDxeEntryPoint (
   IN EFI_HANDLE         ImageHandle,
   IN EFI_SYSTEM_TABLE   *SystemTable
   )
 {
   EFI_STATUS                       Status;
   EFI_GCD_MEMORY_SPACE_DESCRIPTOR  *AllDescMap;
   UINTN                            NumEntries;
   UINTN                            Index;
 
   //
   // Do nothing when SEV is not enabled
   //
   if (!MemEncryptSevIsEnabled ()) {
     return EFI_UNSUPPORTED;
   }
 
@@ -51,22 +54,72 @@ AmdSevDxeEntryPoint (
   if (!EFI_ERROR (Status)) {
     for (Index = 0; Index < NumEntries; Index++) {
       CONST EFI_GCD_MEMORY_SPACE_DESCRIPTOR *Desc;
 
       Desc = &AllDescMap[Index];
       if (Desc->GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo ||
           Desc->GcdMemoryType == EfiGcdMemoryTypeNonExistent) {
         Status = MemEncryptSevClearPageEncMask (
                    0,
                    Desc->BaseAddress,
                    EFI_SIZE_TO_PAGES (Desc->Length),
                    FALSE
                    );
         ASSERT_EFI_ERROR (Status);
       }
     }
 
     FreePool (AllDescMap);
   }
 
+  //
+  // When SMM is enabled, clear the C-bit from SMM Saved State Area
+  //
+  // NOTES: The SavedStateArea address cleared here is before SMBASE
+  // relocation. Currently, we do not clear the SavedStateArea address after
+  // SMBASE is relocated due to the following reasons:
+  //
+  // 1) Guest BIOS never access the relocated SavedStateArea.
+  //
+  // 2) The C-bit works on page-aligned address, but the SavedStateArea
+  // address is not a page-aligned. Theoretically, we could roundup the address
+  // and clear the C-bit of aligned address but looking carefully we found
+  // that some portion of the page contains code -- which will causes a bigger
+  // issues for SEV guest. When SEV is enabled, all the code must be encrypted
+  // otherwise hardware will cause trap.
+  //
+  // We restore the C-bit for this SMM Saved State Area after SMBASE relocation
+  // is completed (See OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c).
+  //
+  if (FeaturePcdGet (PcdSmmSmramRequire)) {
+    UINTN MapPagesBase;
+    UINTN MapPagesCount;
+
+    Status = MemEncryptSevLocateInitialSmramSaveStateMapPages (
+               &MapPagesBase,
+               &MapPagesCount
+               );
+    ASSERT_EFI_ERROR (Status);
+
+    //
+    // Although these pages were set aside (i.e., allocated) by PlatformPei, we
+    // could be after a warm reboot from the OS. Don't leak any stale OS data
+    // to the hypervisor.
+    //
+    ZeroMem ((VOID *)MapPagesBase, EFI_PAGES_TO_SIZE (MapPagesCount));
+
+    Status = MemEncryptSevClearPageEncMask (
+               0,             // Cr3BaseAddress -- use current CR3
+               MapPagesBase,  // BaseAddress
+               MapPagesCount, // NumPages
+               TRUE           // Flush
+               );
+    if (EFI_ERROR (Status)) {
+      DEBUG ((DEBUG_ERROR, "%a: MemEncryptSevClearPageEncMask(): %r\n",
+        __FUNCTION__, Status));
+      ASSERT (FALSE);
+      CpuDeadLoop ();
+    }
+  }
+
   return EFI_SUCCESS;
 }
-- 
2.14.1.3.gb7cf6e02401b



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

* Re: [PATCH 01/20] OvmfPkg/MemEncryptSevLib: rewrap to 79 characters width
  2018-03-02  0:03 ` [PATCH 01/20] OvmfPkg/MemEncryptSevLib: rewrap to 79 characters width Laszlo Ersek
@ 2018-03-02  0:33   ` Kinney, Michael D
  2018-03-02 11:25     ` Laszlo Ersek
  0 siblings, 1 reply; 33+ messages in thread
From: Kinney, Michael D @ 2018-03-02  0:33 UTC (permalink / raw)
  To: Laszlo Ersek, edk2-devel-01, Kinney, Michael D
  Cc: Justen, Jordan L, Brijesh Singh, Ard Biesheuvel

Laszlo,

Sorting #includes looks strange to me.

We usually include the top level environment include
first (e.g. <PiPei.h>) and then the libs, protocols,
ppis, GUIDs grouped together.

If it is a lib module, the produced libs are listed
first followed by the consumed libs.

Mike

> -----Original Message-----
> From: edk2-devel [mailto:edk2-devel-
> bounces@lists.01.org] On Behalf Of Laszlo Ersek
> Sent: Thursday, March 1, 2018 4:04 PM
> To: edk2-devel-01 <edk2-devel@lists.01.org>
> Cc: Justen, Jordan L <jordan.l.justen@intel.com>;
> Brijesh Singh <brijesh.singh@amd.com>; Ard Biesheuvel
> <ard.biesheuvel@linaro.org>
> Subject: [edk2] [PATCH 01/20] OvmfPkg/MemEncryptSevLib:
> rewrap to 79 characters width
> 
> There are many overlong lines; it's hard to work with
> the library like
> this. Rewrap all files to 79 columns.
> 
> Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
> Cc: Brijesh Singh <brijesh.singh@amd.com>
> Cc: Jordan Justen <jordan.l.justen@intel.com>
> Contributed-under: TianoCore Contribution Agreement 1.1
> Signed-off-by: Laszlo Ersek <lersek@redhat.com>
> ---
> 
> OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevL
> ib.inf   |   7 +-
>  OvmfPkg/Include/Library/MemEncryptSevLib.h
> |  20 ++-
> 
> OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.
> h        | 111 ++++++++------
> 
> OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSev
> Lib.c    |  34 +++--
> 
> OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibIn
> ternal.c |   8 +-
> 
> OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevL
> ib.c     |  58 ++++---
> 
> OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.
> c        | 158 +++++++++++++-------
>  7 files changed, 253 insertions(+), 143 deletions(-)
> 
> diff --git
> a/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSe
> vLib.inf
> b/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSe
> vLib.inf
> index 3cfd80a28c1d..81b075194ace 100644
> ---
> a/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSe
> vLib.inf
> +++
> b/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSe
> vLib.inf
> @@ -1,45 +1,48 @@
>  ## @file
>  #  Library provides the helper functions for SEV guest
>  #
>  # Copyright (c) 2017 Advanced Micro Devices. All
> rights reserved.<BR>
>  #
>  #  This program and the accompanying materials
>  #  are licensed and made available under the terms and
> conditions of the BSD
>  #  License which accompanies this distribution. The
> full text of the license
>  #  may be found at http://opensource.org/licenses/bsd-
> license.php
> +#
>  #  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON
> AN "AS IS" BASIS,
> -#  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND,
> EITHER EXPRESS OR IMPLIED.
> +#  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND,
> EITHER EXPRESS OR
> +#  IMPLIED.
>  #
>  #
>  ##
> 
>  [Defines]
>    INF_VERSION                    = 1.25
>    BASE_NAME                      = MemEncryptSevLib
>    FILE_GUID                      = c1594631-3888-4be4-
> 949f-9c630dbc842b
>    MODULE_TYPE                    = BASE
>    VERSION_STRING                 = 1.0
>    LIBRARY_CLASS                  =
> MemEncryptSevLib|PEIM DXE_DRIVER DXE_RUNTIME_DRIVER
> DXE_SMM_DRIVER UEFI_DRIVER
> 
>  #
> -# The following information is for reference only and
> not required by the build tools.
> +# The following information is for reference only and
> not required by the build
> +# tools.
>  #
>  # VALID_ARCHITECTURES           = IA32 X64
>  #
> 
>  [Packages]
>    MdePkg/MdePkg.dec
>    MdeModulePkg/MdeModulePkg.dec
>    OvmfPkg/OvmfPkg.dec
>    UefiCpuPkg/UefiCpuPkg.dec
> 
>  [Sources.X64]
>    MemEncryptSevLibInternal.c
>    X64/MemEncryptSevLib.c
>    X64/VirtualMemory.c
> 
>  [Sources.IA32]
>    MemEncryptSevLibInternal.c
>    Ia32/MemEncryptSevLib.c
> 
>  [LibraryClasses]
> diff --git a/OvmfPkg/Include/Library/MemEncryptSevLib.h
> b/OvmfPkg/Include/Library/MemEncryptSevLib.h
> index b6753762423e..4f3ba9f22cb4 100644
> --- a/OvmfPkg/Include/Library/MemEncryptSevLib.h
> +++ b/OvmfPkg/Include/Library/MemEncryptSevLib.h
> @@ -18,64 +18,68 @@
>  #define _MEM_ENCRYPT_SEV_LIB_H_
> 
>  #include <Base.h>
> 
>  /**
>    Returns a boolean to indicate whether SEV is enabled
> 
>    @retval TRUE           SEV is active
>    @retval FALSE          SEV is not enabled
>    **/
>  BOOLEAN
>  EFIAPI
>  MemEncryptSevIsEnabled (
>    VOID
>    );
> 
>  /**
>    This function clears memory encryption bit for the
> memory region specified
>    by BaseAddress and Number of pages from the current
> page table context.
> 
> -  @param[in]  BaseAddress           The physical
> address that is the start address
> -                                    of a memory
> region.
> -  @param[in]  NumberOfPages         The number of
> pages from start memory region.
> +  @param[in]  BaseAddress           The physical
> address that is the start
> +                                    address of a
> memory region.
> +  @param[in]  NumberOfPages         The number of
> pages from start memory
> +                                    region.
>    @param[in]  Flush                 Flush the caches
> before clearing the bit
>                                      (mostly TRUE
> except MMIO addresses)
> 
> -  @retval RETURN_SUCCESS            The attributes
> were cleared for the memory region.
> +  @retval RETURN_SUCCESS            The attributes
> were cleared for the memory
> +                                    region.
>    @retval RETURN_INVALID_PARAMETER  Number of pages is
> zero.
>    @retval RETURN_UNSUPPORTED        Clearing memory
> encryption attribute is not
>                                      supported
>    **/
>  RETURN_STATUS
>  EFIAPI
>  MemEncryptSevClearPageEncMask (
>    IN PHYSICAL_ADDRESS         Cr3BaseAddress,
>    IN PHYSICAL_ADDRESS         BaseAddress,
>    IN UINTN                    NumberOfPages,
>    IN BOOLEAN                  CacheFlush
>    );
> 
>  /**
>    This function sets memory encryption bit for the
> memory region specified by
>    BaseAddress and Number of pages from the current
> page table context.
> 
> -  @param[in]  BaseAddress           The physical
> address that is the start address
> -                                    of a memory
> region.
> -  @param[in]  NumberOfPages         The number of
> pages from start memory region.
> +  @param[in]  BaseAddress           The physical
> address that is the start
> +                                    address of a
> memory region.
> +  @param[in]  NumberOfPages         The number of
> pages from start memory
> +                                    region.
>    @param[in]  Flush                 Flush the caches
> before clearing the bit
>                                      (mostly TRUE
> except MMIO addresses)
> 
> -  @retval RETURN_SUCCESS            The attributes
> were set for the memory region.
> +  @retval RETURN_SUCCESS            The attributes
> were set for the memory
> +                                    region.
>    @retval RETURN_INVALID_PARAMETER  Number of pages is
> zero.
>    @retval RETURN_UNSUPPORTED        Clearing memory
> encryption attribute is not
>                                      supported
>    **/
>  RETURN_STATUS
>  EFIAPI
>  MemEncryptSevSetPageEncMask (
>    IN PHYSICAL_ADDRESS         Cr3BaseAddress,
>    IN PHYSICAL_ADDRESS         BaseAddress,
>    IN UINTN                    NumberOfPages,
>    IN BOOLEAN                  CacheFlush
>    );
>  #endif // _MEM_ENCRYPT_SEV_LIB_H_
> diff --git
> a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemor
> y.h
> b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemor
> y.h
> index e7b5634b45c1..7dd1bbe0eb26 100644
> ---
> a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemor
> y.h
> +++
> b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemor
> y.h
> @@ -1,212 +1,239 @@
>  /** @file
> 
>    Virtual Memory Management Services to set or clear
> the memory encryption bit
> 
> -Copyright (c) 2006 - 2016, Intel Corporation. All
> rights reserved.<BR>
> -Copyright (c) 2017, AMD Incorporated. All rights
> reserved.<BR>
> +  Copyright (c) 2006 - 2016, Intel Corporation. All
> rights reserved.<BR>
> +  Copyright (c) 2017, AMD Incorporated. All rights
> reserved.<BR>
> 
> -This program and the accompanying materials
> -are licensed and made available under the terms and
> conditions of the BSD License
> -which accompanies this distribution.  The full text of
> the license may be found at
> -http://opensource.org/licenses/bsd-license.php
> +  This program and the accompanying materials are
> licensed and made available
> +  under the terms and conditions of the BSD License
> which accompanies this
> +  distribution.  The full text of the license may be
> found at
> +  http://opensource.org/licenses/bsd-license.php
> 
> -THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN
> "AS IS" BASIS,
> -WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND,
> EITHER EXPRESS OR IMPLIED.
> +  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON
> AN "AS IS" BASIS, WITHOUT
> +  WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER
> EXPRESS OR IMPLIED.
> 
> -Code is derived from
> MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.h
> +  Code is derived from
> MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.h
> 
>  **/
> 
>  #ifndef __VIRTUAL_MEMORY__
>  #define __VIRTUAL_MEMORY__
> 
>  #include <Uefi.h>
>  #include <Library/BaseLib.h>
>  #include <Library/BaseMemoryLib.h>
>  #include <Library/DebugLib.h>
>  #include <Library/MemoryAllocationLib.h>
> 
>  #include <Library/CacheMaintenanceLib.h>
>  #define SYS_CODE64_SEL 0x38
> 
>  #pragma pack(1)
> 
>  //
>  // Page-Map Level-4 Offset (PML4) and
>  // Page-Directory-Pointer Offset (PDPE) entries 4K &
> 2MB
>  //
> 
>  typedef union {
>    struct {
> -    UINT64  Present:1;                // 0 = Not
> present in memory, 1 = Present in memory
> +    UINT64  Present:1;                // 0 = Not
> present in memory,
> +                                      //   1 = Present
> in memory
>      UINT64  ReadWrite:1;              // 0 = Read-
> Only, 1= Read/Write
>      UINT64  UserSupervisor:1;         // 0 =
> Supervisor, 1=User
> -    UINT64  WriteThrough:1;           // 0 = Write-
> Back caching, 1=Write-Through caching
> +    UINT64  WriteThrough:1;           // 0 = Write-
> Back caching,
> +                                      //   1 = Write-
> Through caching
>      UINT64  CacheDisabled:1;          // 0 = Cached,
> 1=Non-Cached
> -    UINT64  Accessed:1;               // 0 = Not
> accessed, 1 = Accessed (set by CPU)
> +    UINT64  Accessed:1;               // 0 = Not
> accessed,
> +                                      //   1 =
> Accessed (set by CPU)
>      UINT64  Reserved:1;               // Reserved
>      UINT64  MustBeZero:2;             // Must Be Zero
>      UINT64  Available:3;              // Available for
> use by system software
>      UINT64  PageTableBaseAddress:40;  // Page Table
> Base Address
>      UINT64  AvabilableHigh:11;        // Available for
> use by system software
>      UINT64  Nx:1;                     // No Execute
> bit
>    } Bits;
>    UINT64    Uint64;
>  } PAGE_MAP_AND_DIRECTORY_POINTER;
> 
>  //
>  // Page Table Entry 4KB
>  //
>  typedef union {
>    struct {
> -    UINT64  Present:1;                // 0 = Not
> present in memory, 1 = Present in memory
> +    UINT64  Present:1;                // 0 = Not
> present in memory,
> +                                      //   1 = Present
> in memory
>      UINT64  ReadWrite:1;              // 0 = Read-
> Only, 1= Read/Write
>      UINT64  UserSupervisor:1;         // 0 =
> Supervisor, 1=User
> -    UINT64  WriteThrough:1;           // 0 = Write-
> Back caching, 1=Write-Through caching
> +    UINT64  WriteThrough:1;           // 0 = Write-
> Back caching,
> +                                      //   1 = Write-
> Through caching
>      UINT64  CacheDisabled:1;          // 0 = Cached,
> 1=Non-Cached
> -    UINT64  Accessed:1;               // 0 = Not
> accessed, 1 = Accessed (set by CPU)
> -    UINT64  Dirty:1;                  // 0 = Not
> Dirty, 1 = written by processor on access to page
> +    UINT64  Accessed:1;               // 0 = Not
> accessed,
> +                                      //   1 =
> Accessed (set by CPU)
> +    UINT64  Dirty:1;                  // 0 = Not
> Dirty, 1 = written by
> +                                      //   processor
> on access to page
>      UINT64  PAT:1;                    //
> -    UINT64  Global:1;                 // 0 = Not
> global page, 1 = global page TLB not cleared on CR3
> write
> +    UINT64  Global:1;                 // 0 = Not
> global page, 1 = global page
> +                                      //   TLB not
> cleared on CR3 write
>      UINT64  Available:3;              // Available for
> use by system software
>      UINT64  PageTableBaseAddress:40;  // Page Table
> Base Address
>      UINT64  AvabilableHigh:11;        // Available for
> use by system software
> -    UINT64  Nx:1;                     // 0 = Execute
> Code, 1 = No Code Execution
> +    UINT64  Nx:1;                     // 0 = Execute
> Code,
> +                                      //   1 = No Code
> Execution
>    } Bits;
>    UINT64    Uint64;
>  } PAGE_TABLE_4K_ENTRY;
> 
>  //
>  // Page Table Entry 2MB
>  //
>  typedef union {
>    struct {
> -    UINT64  Present:1;                // 0 = Not
> present in memory, 1 = Present in memory
> +    UINT64  Present:1;                // 0 = Not
> present in memory,
> +                                      //   1 = Present
> in memory
>      UINT64  ReadWrite:1;              // 0 = Read-
> Only, 1= Read/Write
>      UINT64  UserSupervisor:1;         // 0 =
> Supervisor, 1=User
> -    UINT64  WriteThrough:1;           // 0 = Write-
> Back caching, 1=Write-Through caching
> +    UINT64  WriteThrough:1;           // 0 = Write-
> Back caching,
> +                                      //   1=Write-
> Through caching
>      UINT64  CacheDisabled:1;          // 0 = Cached,
> 1=Non-Cached
> -    UINT64  Accessed:1;               // 0 = Not
> accessed, 1 = Accessed (set by CPU)
> -    UINT64  Dirty:1;                  // 0 = Not
> Dirty, 1 = written by processor on access to page
> +    UINT64  Accessed:1;               // 0 = Not
> accessed,
> +                                      //   1 =
> Accessed (set by CPU)
> +    UINT64  Dirty:1;                  // 0 = Not
> Dirty, 1 = written by
> +                                      //   processor
> on access to page
>      UINT64  MustBe1:1;                // Must be 1
> -    UINT64  Global:1;                 // 0 = Not
> global page, 1 = global page TLB not cleared on CR3
> write
> +    UINT64  Global:1;                 // 0 = Not
> global page, 1 = global page
> +                                      //   TLB not
> cleared on CR3 write
>      UINT64  Available:3;              // Available for
> use by system software
>      UINT64  PAT:1;                    //
>      UINT64  MustBeZero:8;             // Must be zero;
>      UINT64  PageTableBaseAddress:31;  // Page Table
> Base Address
>      UINT64  AvabilableHigh:11;        // Available for
> use by system software
> -    UINT64  Nx:1;                     // 0 = Execute
> Code, 1 = No Code Execution
> +    UINT64  Nx:1;                     // 0 = Execute
> Code,
> +                                      //   1 = No Code
> Execution
>    } Bits;
>    UINT64    Uint64;
>  } PAGE_TABLE_ENTRY;
> 
>  //
>  // Page Table Entry 1GB
>  //
>  typedef union {
>    struct {
> -    UINT64  Present:1;                // 0 = Not
> present in memory, 1 = Present in memory
> +    UINT64  Present:1;                // 0 = Not
> present in memory,
> +                                      //   1 = Present
> in memory
>      UINT64  ReadWrite:1;              // 0 = Read-
> Only, 1= Read/Write
>      UINT64  UserSupervisor:1;         // 0 =
> Supervisor, 1=User
> -    UINT64  WriteThrough:1;           // 0 = Write-
> Back caching, 1=Write-Through caching
> +    UINT64  WriteThrough:1;           // 0 = Write-
> Back caching,
> +                                      //   1 = Write-
> Through caching
>      UINT64  CacheDisabled:1;          // 0 = Cached,
> 1=Non-Cached
> -    UINT64  Accessed:1;               // 0 = Not
> accessed, 1 = Accessed (set by CPU)
> -    UINT64  Dirty:1;                  // 0 = Not
> Dirty, 1 = written by processor on access to page
> +    UINT64  Accessed:1;               // 0 = Not
> accessed,
> +                                      //   1 =
> Accessed (set by CPU)
> +    UINT64  Dirty:1;                  // 0 = Not
> Dirty, 1 = written by
> +                                      //   processor
> on access to page
>      UINT64  MustBe1:1;                // Must be 1
> -    UINT64  Global:1;                 // 0 = Not
> global page, 1 = global page TLB not cleared on CR3
> write
> +    UINT64  Global:1;                 // 0 = Not
> global page, 1 = global page
> +                                      //   TLB not
> cleared on CR3 write
>      UINT64  Available:3;              // Available for
> use by system software
>      UINT64  PAT:1;                    //
>      UINT64  MustBeZero:17;            // Must be zero;
>      UINT64  PageTableBaseAddress:22;  // Page Table
> Base Address
>      UINT64  AvabilableHigh:11;        // Available for
> use by system software
> -    UINT64  Nx:1;                     // 0 = Execute
> Code, 1 = No Code Execution
> +    UINT64  Nx:1;                     // 0 = Execute
> Code,
> +                                      //   1 = No Code
> Execution
>    } Bits;
>    UINT64    Uint64;
>  } PAGE_TABLE_1G_ENTRY;
> 
>  #pragma pack()
> 
>  #define IA32_PG_P                   BIT0
>  #define IA32_PG_RW                  BIT1
>  #define IA32_PG_PS                  BIT7
> 
>  #define PAGING_PAE_INDEX_MASK       0x1FF
> 
>  #define PAGING_4K_ADDRESS_MASK_64
> 0x000FFFFFFFFFF000ull
>  #define PAGING_2M_ADDRESS_MASK_64
> 0x000FFFFFFFE00000ull
>  #define PAGING_1G_ADDRESS_MASK_64
> 0x000FFFFFC0000000ull
> 
>  #define PAGING_L1_ADDRESS_SHIFT     12
>  #define PAGING_L2_ADDRESS_SHIFT     21
>  #define PAGING_L3_ADDRESS_SHIFT     30
>  #define PAGING_L4_ADDRESS_SHIFT     39
> 
>  #define PAGING_PML4E_NUMBER         4
> 
>  #define PAGETABLE_ENTRY_MASK        ((1UL << 9) - 1)
>  #define PML4_OFFSET(x)              ( (x >> 39) &
> PAGETABLE_ENTRY_MASK)
>  #define PDP_OFFSET(x)               ( (x >> 30) &
> PAGETABLE_ENTRY_MASK)
>  #define PDE_OFFSET(x)               ( (x >> 21) &
> PAGETABLE_ENTRY_MASK)
>  #define PTE_OFFSET(x)               ( (x >> 12) &
> PAGETABLE_ENTRY_MASK)
>  #define PAGING_1G_ADDRESS_MASK_64
> 0x000FFFFFC0000000ull
> 
>  #define PAGE_TABLE_POOL_ALIGNMENT   BASE_2MB
>  #define PAGE_TABLE_POOL_UNIT_SIZE   SIZE_2MB
> -#define PAGE_TABLE_POOL_UNIT_PAGES  EFI_SIZE_TO_PAGES
> (PAGE_TABLE_POOL_UNIT_SIZE)
> +#define PAGE_TABLE_POOL_UNIT_PAGES  \
> +  EFI_SIZE_TO_PAGES (PAGE_TABLE_POOL_UNIT_SIZE)
>  #define PAGE_TABLE_POOL_ALIGN_MASK  \
>    (~(EFI_PHYSICAL_ADDRESS)(PAGE_TABLE_POOL_ALIGNMENT -
> 1))
> 
>  typedef struct {
>    VOID            *NextPool;
>    UINTN           Offset;
>    UINTN           FreePages;
>  } PAGE_TABLE_POOL;
> 
> 
> 
>  /**
> -  This function clears memory encryption bit for the
> memory region specified by PhysicalAddress
> -  and length from the current page table context.
> +  This function clears memory encryption bit for the
> memory region specified by
> +  PhysicalAddress and length from the current page
> table context.
> 
> -  @param[in]  PhysicalAddress         The physical
> address that is the start address of a memory region.
> +  @param[in]  PhysicalAddress         The physical
> address that is the start
> +                                      address of a
> memory region.
>    @param[in]  Length                  The length of
> memory region
> -  @param[in]  Flush                   Flush the caches
> before applying the encryption mask
> +  @param[in]  Flush                   Flush the caches
> before applying the
> +                                      encryption mask
> 
> -  @retval RETURN_SUCCESS              The attributes
> were cleared for the memory region.
> +  @retval RETURN_SUCCESS              The attributes
> were cleared for the
> +                                      memory region.
>    @retval RETURN_INVALID_PARAMETER    Number of pages
> is zero.
> -  @retval RETURN_UNSUPPORTED          Setting the
> memory encyrption attribute is not supported
> +  @retval RETURN_UNSUPPORTED          Setting the
> memory encyrption attribute
> +                                      is not supported
>  **/
>  RETURN_STATUS
>  EFIAPI
>  InternalMemEncryptSevSetMemoryDecrypted (
>    IN  PHYSICAL_ADDRESS     Cr3BaseAddress,
>    IN  PHYSICAL_ADDRESS     PhysicalAddress,
>    IN  UINT64               Length,
>    IN  BOOLEAN              CacheFlush
>    );
> 
>  /**
>    This function sets memory encryption bit for the
> memory region specified by
>    PhysicalAddress and length from the current page
> table context.
> 
> -  @param[in]  PhysicalAddress         The physical
> address that is the start address
> -                                      of a memory
> region.
> +  @param[in]  PhysicalAddress         The physical
> address that is the start
> +                                      address of a
> memory region.
>    @param[in]  Length                  The length of
> memory region
>    @param[in]  Flush                   Flush the caches
> before applying the
>                                        encryption mask
> 
> -  @retval RETURN_SUCCESS              The attributes
> were cleared for the memory region.
> +  @retval RETURN_SUCCESS              The attributes
> were cleared for the
> +                                      memory region.
>    @retval RETURN_INVALID_PARAMETER    Number of pages
> is zero.
> -  @retval RETURN_UNSUPPORTED          Setting the
> memory encyrption attribute is
> -                                      not supported
> +  @retval RETURN_UNSUPPORTED          Setting the
> memory encyrption attribute
> +                                      is not supported
>  **/
>  RETURN_STATUS
>  EFIAPI
>  InternalMemEncryptSevSetMemoryEncrypted (
>    IN  PHYSICAL_ADDRESS     Cr3BaseAddress,
>    IN  PHYSICAL_ADDRESS     PhysicalAddress,
>    IN  UINT64               Length,
>    IN  BOOLEAN              CacheFlush
>    );
> 
>  #endif
> diff --git
> a/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptS
> evLib.c
> b/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptS
> evLib.c
> index a2ea99019917..d1130df2d0e7 100644
> ---
> a/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptS
> evLib.c
> +++
> b/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptS
> evLib.c
> @@ -1,84 +1,90 @@
>  /** @file
> 
>    Secure Encrypted Virtualization (SEV) library helper
> function
> 
>    Copyright (c) 2017, AMD Incorporated. All rights
> reserved.<BR>
> 
> -  This program and the accompanying materials
> -  are licensed and made available under the terms and
> conditions of the BSD
> -  License which accompanies this distribution.  The
> full text of the license may
> -  be found at http://opensource.org/licenses/bsd-
> license.php
> +  This program and the accompanying materials are
> licensed and made available
> +  under the terms and conditions of the BSD License
> which accompanies this
> +  distribution.  The full text of the license may be
> found at
> +  http://opensource.org/licenses/bsd-license.php
> 
>    THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON
> AN "AS IS" BASIS,
>    WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND,
> EITHER EXPRESS OR IMPLIED.
> 
>  **/
> 
>  #include <Library/BaseLib.h>
>  #include <Library/DebugLib.h>
>  #include <Register/Cpuid.h>
>  #include <Register/Amd/Cpuid.h>
>  #include <Register/Amd/Msr.h>
>  #include <Library/MemEncryptSevLib.h>
> 
>  /**
>    This function clears memory encryption bit for the
> memory region specified
>    by BaseAddress and Number of pages from the current
> page table context.
> 
> -  @param[in]  Cr3BaseAddress        Cr3 Base Address
> (if zero then use current CR3)
> -  @param[in]  BaseAddress           The physical
> address that is the start address
> -                                    of a memory
> region.
> -  @param[in]  NumberOfPages         The number of
> pages from start memory region.
> +  @param[in]  Cr3BaseAddress        Cr3 Base Address
> (if zero then use current
> +                                    CR3)
> +  @param[in]  BaseAddress           The physical
> address that is the start
> +                                    address of a
> memory region.
> +  @param[in]  NumberOfPages         The number of
> pages from start memory
> +                                    region.
>    @param[in]  Flush                 Flush the caches
> before clearing the bit
>                                      (mostly TRUE
> except MMIO addresses)
> 
> -  @retval RETURN_SUCCESS            The attributes
> were cleared for the memory region.
> +  @retval RETURN_SUCCESS            The attributes
> were cleared for the memory
> +                                    region.
>    @retval RETURN_INVALID_PARAMETER  Number of pages is
> zero.
>    @retval RETURN_UNSUPPORTED        Clearing memory
> encryption attribute is not
>                                      supported
>    **/
>  RETURN_STATUS
>  EFIAPI
>  MemEncryptSevClearPageEncMask (
>    IN PHYSICAL_ADDRESS         Cr3BaseAddress,
>    IN PHYSICAL_ADDRESS         BaseAddress,
>    IN UINTN                    NumberOfPages,
>    IN BOOLEAN                  Flush
>    )
>  {
>    //
>    // Memory encryption bit is not accessible in 32-bit
> mode
>    //
>    return RETURN_UNSUPPORTED;
>  }
> 
>  /**
>    This function sets memory encryption bit for the
> memory region specified by
>    BaseAddress and Number of pages from the current
> page table context.
> 
> -  @param[in]  Cr3BaseAddress        Cr3 Base Address
> (if zero then use current CR3)
> -  @param[in]  BaseAddress           The physical
> address that is the start address
> -                                    of a memory
> region.
> -  @param[in]  NumberOfPages         The number of
> pages from start memory region.
> +  @param[in]  Cr3BaseAddress        Cr3 Base Address
> (if zero then use current
> +                                    CR3)
> +  @param[in]  BaseAddress           The physical
> address that is the start
> +                                    address of a
> memory region.
> +  @param[in]  NumberOfPages         The number of
> pages from start memory
> +                                    region.
>    @param[in]  Flush                 Flush the caches
> before clearing the bit
>                                      (mostly TRUE
> except MMIO addresses)
> 
> -  @retval RETURN_SUCCESS            The attributes
> were set for the memory region.
> +  @retval RETURN_SUCCESS            The attributes
> were set for the memory
> +                                    region.
>    @retval RETURN_INVALID_PARAMETER  Number of pages is
> zero.
>    @retval RETURN_UNSUPPORTED        Clearing memory
> encryption attribute is not
>                                      supported
>    **/
>  RETURN_STATUS
>  EFIAPI
>  MemEncryptSevSetPageEncMask (
>    IN PHYSICAL_ADDRESS         Cr3BaseAddress,
>    IN PHYSICAL_ADDRESS         BaseAddress,
>    IN UINTN                    NumberOfPages,
>    IN BOOLEAN                  Flush
>    )
>  {
>    //
>    // Memory encryption bit is not accessible in 32-bit
> mode
>    //
>    return RETURN_UNSUPPORTED;
>  }
> diff --git
> a/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLib
> Internal.c
> b/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLib
> Internal.c
> index 002f079c7eb3..ff561236d819 100644
> ---
> a/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLib
> Internal.c
> +++
> b/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLib
> Internal.c
> @@ -1,30 +1,30 @@
>  /** @file
> 
>    Secure Encrypted Virtualization (SEV) library helper
> function
> 
>    Copyright (c) 2017, AMD Incorporated. All rights
> reserved.<BR>
> 
> -  This program and the accompanying materials
> -  are licensed and made available under the terms and
> conditions of the BSD
> -  License which accompanies this distribution.  The
> full text of the license may
> -  be found at http://opensource.org/licenses/bsd-
> license.php
> +  This program and the accompanying materials are
> licensed and made available
> +  under the terms and conditions of the BSD License
> which accompanies this
> +  distribution.  The full text of the license may be
> found at
> +  http://opensource.org/licenses/bsd-license.php
> 
>    THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON
> AN "AS IS" BASIS,
>    WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND,
> EITHER EXPRESS OR IMPLIED.
> 
>  **/
> 
>  #include <Library/BaseLib.h>
>  #include <Library/DebugLib.h>
>  #include <Register/Cpuid.h>
>  #include <Register/Amd/Cpuid.h>
>  #include <Register/Amd/Msr.h>
>  #include <Library/MemEncryptSevLib.h>
> 
>  STATIC BOOLEAN mSevStatus = FALSE;
>  STATIC BOOLEAN mSevStatusChecked = FALSE;
> 
>  /**
> 
>    Returns a boolean to indicate whether SEV is enabled
> 
> diff --git
> a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSe
> vLib.c
> b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSe
> vLib.c
> index 9ec76708bd7b..4b7fdf7d044d 100644
> ---
> a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSe
> vLib.c
> +++
> b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSe
> vLib.c
> @@ -1,84 +1,98 @@
>  /** @file
> 
>    Secure Encrypted Virtualization (SEV) library helper
> function
> 
>    Copyright (c) 2017, AMD Incorporated. All rights
> reserved.<BR>
> 
> -  This program and the accompanying materials
> -  are licensed and made available under the terms and
> conditions of the BSD
> -  License which accompanies this distribution.  The
> full text of the license may
> -  be found at http://opensource.org/licenses/bsd-
> license.php
> +  This program and the accompanying materials are
> licensed and made available
> +  under the terms and conditions of the BSD License
> which accompanies this
> +  distribution.  The full text of the license may be
> found at
> +  http://opensource.org/licenses/bsd-license.php
> 
>    THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON
> AN "AS IS" BASIS,
>    WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND,
> EITHER EXPRESS OR IMPLIED.
> 
>  **/
> 
>  #include <Library/BaseLib.h>
>  #include <Library/DebugLib.h>
>  #include <Register/Cpuid.h>
>  #include <Register/Amd/Cpuid.h>
>  #include <Register/Amd/Msr.h>
>  #include <Library/MemEncryptSevLib.h>
> 
>  #include "VirtualMemory.h"
> 
>  /**
> 
>    This function clears memory encryption bit for the
> memory region specified by
>    BaseAddress and Number of pages from the current
> page table context.
> 
> -  @param[in]  Cr3BaseAddress          Cr3 Base Address
> (if zero then use current CR3)
> -  @param[in]  BaseAddress             The physical
> address that is the start address
> -                                      of a memory
> region.
> -  @param[in]  NumberOfPages           The number of
> pages from start memory region.
> +  @param[in]  Cr3BaseAddress          Cr3 Base Address
> (if zero then use
> +                                      current CR3)
> +  @param[in]  BaseAddress             The physical
> address that is the start
> +                                      address of a
> memory region.
> +  @param[in]  NumberOfPages           The number of
> pages from start memory
> +                                      region.
>    @param[in]  Flush                   Flush the caches
> before clearing the bit
>                                        (mostly TRUE
> except MMIO addresses)
> 
> -  @retval RETURN_SUCCESS              The attributes
> were cleared for the memory
> -                                      region.
> +  @retval RETURN_SUCCESS              The attributes
> were cleared for the
> +                                      memory region.
>    @retval RETURN_INVALID_PARAMETER    Number of pages
> is zero.
> -  @retval RETURN_UNSUPPORTED          Clearing the
> memory encryption attribute is
> -                                      not supported
> +  @retval RETURN_UNSUPPORTED          Clearing the
> memory encryption attribute
> +                                      is not supported
>    **/
>  RETURN_STATUS
>  EFIAPI
>  MemEncryptSevClearPageEncMask (
>    IN PHYSICAL_ADDRESS         Cr3BaseAddress,
>    IN PHYSICAL_ADDRESS         BaseAddress,
>    IN UINTN                    NumPages,
>    IN BOOLEAN                  Flush
>    )
>  {
> -  return InternalMemEncryptSevSetMemoryDecrypted
> (Cr3BaseAddress, BaseAddress,
> EFI_PAGES_TO_SIZE(NumPages), Flush);
> +  return InternalMemEncryptSevSetMemoryDecrypted (
> +           Cr3BaseAddress,
> +           BaseAddress,
> +           EFI_PAGES_TO_SIZE (NumPages),
> +           Flush
> +           );
>  }
> 
>  /**
> 
>    This function clears memory encryption bit for the
> memory region specified by
>    BaseAddress and Number of pages from the current
> page table context.
> 
> -  @param[in]  Cr3BaseAddress          Cr3 Base Address
> (if zero then use current CR3)
> -  @param[in]  BaseAddress             The physical
> address that is the start address
> -                                      of a memory
> region.
> -  @param[in]  NumberOfPages           The number of
> pages from start memory region.
> +  @param[in]  Cr3BaseAddress          Cr3 Base Address
> (if zero then use
> +                                      current CR3)
> +  @param[in]  BaseAddress             The physical
> address that is the start
> +                                      address of a
> memory region.
> +  @param[in]  NumberOfPages           The number of
> pages from start memory
> +                                      region.
>    @param[in]  Flush                   Flush the caches
> before clearing the bit
>                                        (mostly TRUE
> except MMIO addresses)
> 
> -  @retval RETURN_SUCCESS              The attributes
> were cleared for the memory
> -                                      region.
> +  @retval RETURN_SUCCESS              The attributes
> were cleared for the
> +                                      memory region.
>    @retval RETURN_INVALID_PARAMETER    Number of pages
> is zero.
> -  @retval RETURN_UNSUPPORTED          Clearing the
> memory encryption attribute is
> -                                      not supported
> +  @retval RETURN_UNSUPPORTED          Clearing the
> memory encryption attribute
> +                                      is not supported
>    **/
>  RETURN_STATUS
>  EFIAPI
>  MemEncryptSevSetPageEncMask (
>    IN PHYSICAL_ADDRESS         Cr3BaseAddress,
>    IN PHYSICAL_ADDRESS         BaseAddress,
>    IN UINTN                    NumPages,
>    IN BOOLEAN                  Flush
>    )
>  {
> -  return InternalMemEncryptSevSetMemoryEncrypted
> (Cr3BaseAddress, BaseAddress,
> EFI_PAGES_TO_SIZE(NumPages), Flush);
> +  return InternalMemEncryptSevSetMemoryEncrypted (
> +           Cr3BaseAddress,
> +           BaseAddress,
> +           EFI_PAGES_TO_SIZE (NumPages),
> +           Flush
> +           );
>  }
> diff --git
> a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemor
> y.c
> b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemor
> y.c
> index 4185874c99b8..65b8babaac44 100644
> ---
> a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemor
> y.c
> +++
> b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemor
> y.c
> @@ -1,36 +1,36 @@
>  /** @file
> 
>    Virtual Memory Management Services to set or clear
> the memory encryption bit
> 
> -Copyright (c) 2006 - 2016, Intel Corporation. All
> rights reserved.<BR>
> -Copyright (c) 2017, AMD Incorporated. All rights
> reserved.<BR>
> +  Copyright (c) 2006 - 2016, Intel Corporation. All
> rights reserved.<BR>
> +  Copyright (c) 2017, AMD Incorporated. All rights
> reserved.<BR>
> 
> -This program and the accompanying materials
> -are licensed and made available under the terms and
> conditions of the BSD License
> -which accompanies this distribution.  The full text of
> the license may be found at
> -http://opensource.org/licenses/bsd-license.php
> +  This program and the accompanying materials are
> licensed and made available
> +  under the terms and conditions of the BSD License
> which accompanies this
> +  distribution.  The full text of the license may be
> found at
> +  http://opensource.org/licenses/bsd-license.php
> 
> -THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN
> "AS IS" BASIS,
> -WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND,
> EITHER EXPRESS OR IMPLIED.
> +  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON
> AN "AS IS" BASIS, WITHOUT
> +  WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER
> EXPRESS OR IMPLIED.
> 
> -Code is derived from
> MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c
> +  Code is derived from
> MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c
> 
>  **/
> 
>  #include <Library/CpuLib.h>
>  #include <Register/Cpuid.h>
>  #include <Register/Amd/Cpuid.h>
> 
>  #include "VirtualMemory.h"
> 
>  STATIC BOOLEAN mAddressEncMaskChecked = FALSE;
>  STATIC UINT64  mAddressEncMask;
>  STATIC PAGE_TABLE_POOL   *mPageTablePool = NULL;
> 
>  typedef enum {
>     SetCBit,
>     ClearCBit
>  } MAP_RANGE_MODE;
> 
>  /**
>    Get the memory encryption mask
> @@ -52,45 +52,46 @@ GetMemEncryptionAddressMask (
>    }
> 
>    //
>    // CPUID Fn8000_001F[EBX] Bit 0:5 (memory encryption
> bit position)
>    //
>    AsmCpuid (CPUID_MEMORY_ENCRYPTION_INFO, NULL,
> &Ebx.Uint32, NULL, NULL);
>    EncryptionMask = LShiftU64 (1, Ebx.Bits.PtePosBits);
> 
>    mAddressEncMask = EncryptionMask &
> PAGING_1G_ADDRESS_MASK_64;
>    mAddressEncMaskChecked = TRUE;
> 
>    return mAddressEncMask;
>  }
> 
>  /**
>    Initialize a buffer pool for page table use only.
> 
>    To reduce the potential split operation on page
> table, the pages reserved for
>    page table should be allocated in the times of
> PAGE_TABLE_POOL_UNIT_PAGES and
>    at the boundary of PAGE_TABLE_POOL_ALIGNMENT. So the
> page pool is always
> -  initialized with number of pages greater than or
> equal to the given PoolPages.
> +  initialized with number of pages greater than or
> equal to the given
> +  PoolPages.
> 
>    Once the pages in the pool are used up, this method
> should be called again to
> -  reserve at least another PAGE_TABLE_POOL_UNIT_PAGES.
> Usually this won't happen
> -  often in practice.
> +  reserve at least another PAGE_TABLE_POOL_UNIT_PAGES.
> Usually this won't
> +  happen often in practice.
> 
>    @param[in] PoolPages      The least page number of
> the pool to be created.
> 
>    @retval TRUE    The pool is initialized
> successfully.
>    @retval FALSE   The memory is out of resource.
>  **/
>  STATIC
>  BOOLEAN
>  InitializePageTablePool (
>    IN  UINTN                           PoolPages
>    )
>  {
>    VOID                      *Buffer;
> 
>    //
>    // Always reserve at least
> PAGE_TABLE_POOL_UNIT_PAGES, including one page for
>    // header.
>    //
>    PoolPages += 1;   // Add one page for header.
>    PoolPages = ((PoolPages - 1) /
> PAGE_TABLE_POOL_UNIT_PAGES + 1) *
> @@ -166,89 +167,96 @@ AllocatePageTableMemory (
> 
>    mPageTablePool->Offset     += EFI_PAGES_TO_SIZE
> (Pages);
>    mPageTablePool->FreePages  -= Pages;
> 
>    DEBUG ((
>      DEBUG_VERBOSE,
>      "%a:%a: Buffer=0x%Lx Pages=%ld\n",
>      gEfiCallerBaseName,
>      __FUNCTION__,
>      Buffer,
>      Pages
>      ));
> 
>    return Buffer;
>  }
> 
> 
>  /**
>    Split 2M page to 4K.
> 
> -  @param[in]      PhysicalAddress       Start physical
> address the 2M page covered.
> +  @param[in]      PhysicalAddress       Start physical
> address the 2M page
> +                                        covered.
>    @param[in, out] PageEntry2M           Pointer to 2M
> page entry.
>    @param[in]      StackBase             Stack base
> address.
>    @param[in]      StackSize             Stack size.
> 
>  **/
>  STATIC
>  VOID
>  Split2MPageTo4K (
>    IN        PHYSICAL_ADDRESS
> PhysicalAddress,
>    IN  OUT   UINT64
> *PageEntry2M,
>    IN        PHYSICAL_ADDRESS               StackBase,
>    IN        UINTN                          StackSize
>    )
>  {
>    PHYSICAL_ADDRESS                  PhysicalAddress4K;
>    UINTN
> IndexOfPageTableEntries;
>    PAGE_TABLE_4K_ENTRY               *PageTableEntry,
> *PageTableEntry1;
>    UINT64                            AddressEncMask;
> 
>    PageTableEntry = AllocatePageTableMemory(1);
> 
>    PageTableEntry1 = PageTableEntry;
> 
>    AddressEncMask = GetMemEncryptionAddressMask ();
> 
>    ASSERT (PageTableEntry != NULL);
>    ASSERT (*PageEntry2M & AddressEncMask);
> 
>    PhysicalAddress4K = PhysicalAddress;
> -  for (IndexOfPageTableEntries = 0;
> IndexOfPageTableEntries < 512;
> IndexOfPageTableEntries++, PageTableEntry++,
> PhysicalAddress4K += SIZE_4KB) {
> +  for (IndexOfPageTableEntries = 0;
> +       IndexOfPageTableEntries < 512;
> +       (IndexOfPageTableEntries++,
> +        PageTableEntry++,
> +        PhysicalAddress4K += SIZE_4KB)) {
>      //
>      // Fill in the Page Table entries
>      //
>      PageTableEntry->Uint64 = (UINT64)
> PhysicalAddress4K | AddressEncMask;
>      PageTableEntry->Bits.ReadWrite = 1;
>      PageTableEntry->Bits.Present = 1;
> -    if ((PhysicalAddress4K >= StackBase) &&
> (PhysicalAddress4K < StackBase + StackSize)) {
> +    if ((PhysicalAddress4K >= StackBase) &&
> +        (PhysicalAddress4K < StackBase + StackSize)) {
>        //
>        // Set Nx bit for stack.
>        //
>        PageTableEntry->Bits.Nx = 1;
>      }
>    }
> 
>    //
>    // Fill in 2M page entry.
>    //
> -  *PageEntry2M = (UINT64) (UINTN) PageTableEntry1 |
> IA32_PG_P | IA32_PG_RW | AddressEncMask;
> +  *PageEntry2M = ((UINT64)(UINTN)PageTableEntry1 |
> +                  IA32_PG_P | IA32_PG_RW |
> AddressEncMask);
>  }
> 
>  /**
>    Set one page of page table pool memory to be read-
> only.
> 
>    @param[in] PageTableBase    Base address of page
> table (CR3).
>    @param[in] Address          Start address of a page
> to be set as read-only.
>    @param[in] Level4Paging     Level 4 paging flag.
> 
>  **/
>  STATIC
>  VOID
>  SetPageTablePoolReadOnly (
>    IN  UINTN                             PageTableBase,
>    IN  EFI_PHYSICAL_ADDRESS              Address,
>    IN  BOOLEAN                           Level4Paging
>    )
>  {
>    UINTN                 Index;
>    UINTN                 EntryIndex;
> @@ -374,96 +382,108 @@ EnablePageTableProtection (
>    PAGE_TABLE_POOL         *HeadPool;
>    PAGE_TABLE_POOL         *Pool;
>    UINT64                  PoolSize;
>    EFI_PHYSICAL_ADDRESS    Address;
> 
>    if (mPageTablePool == NULL) {
>      return;
>    }
> 
>    //
>    // SetPageTablePoolReadOnly might update
> mPageTablePool. It's safer to
>    // remember original one in advance.
>    //
>    HeadPool = mPageTablePool;
>    Pool = HeadPool;
>    do {
>      Address  = (EFI_PHYSICAL_ADDRESS)(UINTN)Pool;
>      PoolSize = Pool->Offset + EFI_PAGES_TO_SIZE (Pool-
> >FreePages);
> 
>      //
> -    // The size of one pool must be multiple of
> PAGE_TABLE_POOL_UNIT_SIZE, which
> -    // is one of page size of the processor (2MB by
> default). Let's apply the
> -    // protection to them one by one.
> +    // The size of one pool must be multiple of
> PAGE_TABLE_POOL_UNIT_SIZE,
> +    // which is one of page size of the processor (2MB
> by default). Let's apply
> +    // the protection to them one by one.
>      //
>      while (PoolSize > 0) {
>        SetPageTablePoolReadOnly(PageTableBase, Address,
> Level4Paging);
>        Address   += PAGE_TABLE_POOL_UNIT_SIZE;
>        PoolSize  -= PAGE_TABLE_POOL_UNIT_SIZE;
>      }
> 
>      Pool = Pool->NextPool;
>    } while (Pool != HeadPool);
> 
>  }
> 
> 
>  /**
>    Split 1G page to 2M.
> 
> -  @param[in]      PhysicalAddress       Start physical
> address the 1G page covered.
> +  @param[in]      PhysicalAddress       Start physical
> address the 1G page
> +                                        covered.
>    @param[in, out] PageEntry1G           Pointer to 1G
> page entry.
>    @param[in]      StackBase             Stack base
> address.
>    @param[in]      StackSize             Stack size.
> 
>  **/
>  STATIC
>  VOID
>  Split1GPageTo2M (
>    IN          PHYSICAL_ADDRESS
> PhysicalAddress,
>    IN  OUT     UINT64
> *PageEntry1G,
>    IN          PHYSICAL_ADDRESS
> StackBase,
>    IN          UINTN                          StackSize
>    )
>  {
>    PHYSICAL_ADDRESS                  PhysicalAddress2M;
>    UINTN
> IndexOfPageDirectoryEntries;
>    PAGE_TABLE_ENTRY
> *PageDirectoryEntry;
>    UINT64                            AddressEncMask;
> 
>    PageDirectoryEntry = AllocatePageTableMemory(1);
> 
>    AddressEncMask = GetMemEncryptionAddressMask ();
>    ASSERT (PageDirectoryEntry != NULL);
>    ASSERT (*PageEntry1G & GetMemEncryptionAddressMask
> ());
>    //
>    // Fill in 1G page entry.
>    //
> -  *PageEntry1G = (UINT64) (UINTN) PageDirectoryEntry |
> IA32_PG_P | IA32_PG_RW | AddressEncMask;
> +  *PageEntry1G = ((UINT64)(UINTN)PageDirectoryEntry |
> +                  IA32_PG_P | IA32_PG_RW |
> AddressEncMask);
> 
>    PhysicalAddress2M = PhysicalAddress;
> -  for (IndexOfPageDirectoryEntries = 0;
> IndexOfPageDirectoryEntries < 512;
> IndexOfPageDirectoryEntries++, PageDirectoryEntry++,
> PhysicalAddress2M += SIZE_2MB) {
> -    if ((PhysicalAddress2M < StackBase + StackSize) &&
> ((PhysicalAddress2M + SIZE_2MB) > StackBase)) {
> +  for (IndexOfPageDirectoryEntries = 0;
> +       IndexOfPageDirectoryEntries < 512;
> +       (IndexOfPageDirectoryEntries++,
> +        PageDirectoryEntry++,
> +        PhysicalAddress2M += SIZE_2MB)) {
> +    if ((PhysicalAddress2M < StackBase + StackSize) &&
> +        ((PhysicalAddress2M + SIZE_2MB) > StackBase))
> {
>        //
>        // Need to split this 2M page that covers stack
> range.
>        //
> -      Split2MPageTo4K (PhysicalAddress2M, (UINT64 *)
> PageDirectoryEntry, StackBase, StackSize);
> +      Split2MPageTo4K (
> +        PhysicalAddress2M,
> +        (UINT64 *)PageDirectoryEntry,
> +        StackBase,
> +        StackSize
> +        );
>      } else {
>        //
>        // Fill in the Page Directory entries
>        //
>        PageDirectoryEntry->Uint64 = (UINT64)
> PhysicalAddress2M | AddressEncMask;
>        PageDirectoryEntry->Bits.ReadWrite = 1;
>        PageDirectoryEntry->Bits.Present = 1;
>        PageDirectoryEntry->Bits.MustBe1 = 1;
>      }
>    }
>  }
> 
> 
>  /**
>    Set or Clear the memory encryption bit
> 
>    @param[in]      PagetablePoint        Page table
> entry pointer (PTE).
>    @param[in]      Mode                  Set or Clear
> encryption bit
> 
>  **/
> @@ -510,62 +530,63 @@ VOID
>  DisableReadOnlyPageWriteProtect (
>    VOID
>    )
>  {
>    AsmWriteCr0 (AsmReadCr0() & ~BIT16);
>  }
> 
>  /**
>   Enable Write Protect on pages marked as read-only.
>  **/
>  VOID
>  EnableReadOnlyPageWriteProtect (
>    VOID
>    )
>  {
>    AsmWriteCr0 (AsmReadCr0() | BIT16);
>  }
> 
> 
>  /**
> -  This function either sets or clears memory
> encryption bit for the memory region
> -  specified by PhysicalAddress and length from the
> current page table context.
> +  This function either sets or clears memory
> encryption bit for the memory
> +  region specified by PhysicalAddress and length from
> the current page table
> +  context.
> 
>    The function iterates through the physicalAddress
> one page at a time, and set
>    or clears the memory encryption mask in the page
> table. If it encounters
>    that a given physical address range is part of large
> page then it attempts to
>    change the attribute at one go (based on size),
> otherwise it splits the
>    large pages into smaller (e.g 2M page into 4K pages)
> and then try to set or
>    clear the encryption bit on the smallest page size.
> 
>    @param[in]  PhysicalAddress         The physical
> address that is the start
>                                        address of a
> memory region.
>    @param[in]  Length                  The length of
> memory region
>    @param[in]  Mode                    Set or Clear
> mode
>    @param[in]  Flush                   Flush the caches
> before applying the
>                                        encryption mask
> 
> -  @retval RETURN_SUCCESS              The attributes
> were cleared for the memory
> -                                      region.
> +  @retval RETURN_SUCCESS              The attributes
> were cleared for the
> +                                      memory region.
>    @retval RETURN_INVALID_PARAMETER    Number of pages
> is zero.
> -  @retval RETURN_UNSUPPORTED          Setting the
> memory encyrption attribute is
> -                                      not supported
> +  @retval RETURN_UNSUPPORTED          Setting the
> memory encyrption attribute
> +                                      is not supported
>  **/
> 
>  STATIC
>  RETURN_STATUS
>  EFIAPI
>  SetMemoryEncDec (
>    IN    PHYSICAL_ADDRESS         Cr3BaseAddress,
>    IN    PHYSICAL_ADDRESS         PhysicalAddress,
>    IN    UINTN                    Length,
>    IN    MAP_RANGE_MODE           Mode,
>    IN    BOOLEAN                  CacheFlush
>    )
>  {
>    PAGE_MAP_AND_DIRECTORY_POINTER *PageMapLevel4Entry;
>    PAGE_MAP_AND_DIRECTORY_POINTER
> *PageUpperDirectoryPointerEntry;
>    PAGE_MAP_AND_DIRECTORY_POINTER
> *PageDirectoryPointerEntry;
>    PAGE_TABLE_1G_ENTRY
> *PageDirectory1GEntry;
>    PAGE_TABLE_ENTRY
> *PageDirectory2MEntry;
>    PAGE_TABLE_4K_ENTRY            *PageTableEntry;
>    UINT64                         PgTableMask;
> @@ -584,81 +605,84 @@ SetMemoryEncDec (
>      (Mode == SetCBit) ? "Encrypt" : "Decrypt",
>      (UINT32)CacheFlush
>      ));
> 
>    //
>    // Check if we have a valid memory encryption mask
>    //
>    AddressEncMask = GetMemEncryptionAddressMask ();
>    if (!AddressEncMask) {
>      return RETURN_ACCESS_DENIED;
>    }
> 
>    PgTableMask = AddressEncMask | EFI_PAGE_MASK;
> 
>    if (Length == 0) {
>      return RETURN_INVALID_PARAMETER;
>    }
> 
>    //
>    // We are going to change the memory encryption
> attribute from C=0 -> C=1 or
> -  // vice versa Flush the caches to ensure that data
> is written into memory with
> -  // correct C-bit
> +  // vice versa Flush the caches to ensure that data
> is written into memory
> +  // with correct C-bit
>    //
>    if (CacheFlush) {
>      WriteBackInvalidateDataCacheRange((VOID*)
> (UINTN)PhysicalAddress, Length);
>    }
> 
>    //
>    // Make sure that the page table is changeable.
>    //
>    IsWpEnabled = IsReadOnlyPageWriteProtected ();
>    if (IsWpEnabled) {
>      DisableReadOnlyPageWriteProtect ();
>    }
> 
>    Status = EFI_SUCCESS;
> 
>    while (Length)
>    {
>      //
>      // If Cr3BaseAddress is not specified then read
> the current CR3
>      //
>      if (Cr3BaseAddress == 0) {
>        Cr3BaseAddress = AsmReadCr3();
>      }
> 
>      PageMapLevel4Entry = (VOID*) (Cr3BaseAddress &
> ~PgTableMask);
>      PageMapLevel4Entry +=
> PML4_OFFSET(PhysicalAddress);
>      if (!PageMapLevel4Entry->Bits.Present) {
>        DEBUG ((
>          DEBUG_ERROR,
>          "%a:%a: bad PML4 for Physical=0x%Lx\n",
>          gEfiCallerBaseName,
>          __FUNCTION__,
>          PhysicalAddress
>          ));
>        Status = RETURN_NO_MAPPING;
>        goto Done;
>      }
> 
> -    PageDirectory1GEntry = (VOID*)
> ((PageMapLevel4Entry->Bits.PageTableBaseAddress<<12) &
> ~PgTableMask);
> +    PageDirectory1GEntry = (VOID *)(
> +                             (PageMapLevel4Entry-
> >Bits.PageTableBaseAddress <<
> +                              12) & ~PgTableMask
> +                             );
>      PageDirectory1GEntry +=
> PDP_OFFSET(PhysicalAddress);
>      if (!PageDirectory1GEntry->Bits.Present) {
>        DEBUG ((
>          DEBUG_ERROR,
>          "%a:%a: bad PDPE for Physical=0x%Lx\n",
>          gEfiCallerBaseName,
>          __FUNCTION__,
>          PhysicalAddress
>          ));
>        Status = RETURN_NO_MAPPING;
>        goto Done;
>      }
> 
>      //
>      // If the MustBe1 bit is not 1, it's not actually
> a 1GB entry
>      //
>      if (PageDirectory1GEntry->Bits.MustBe1) {
>        //
>        // Valid 1GB page
>        // If we have at least 1GB to go, we can just
> update this entry
> @@ -668,90 +692,110 @@ SetMemoryEncDec (
>          DEBUG ((
>            DEBUG_VERBOSE,
>            "%a:%a: updated 1GB entry for
> Physical=0x%Lx\n",
>            gEfiCallerBaseName,
>            __FUNCTION__,
>            PhysicalAddress
>            ));
>          PhysicalAddress += BIT30;
>          Length -= BIT30;
>        } else {
>          //
>          // We must split the page
>          //
>          DEBUG ((
>            DEBUG_VERBOSE,
>            "%a:%a: splitting 1GB page for
> Physical=0x%Lx\n",
>            gEfiCallerBaseName,
>            __FUNCTION__,
>            PhysicalAddress
>            ));
> -        Split1GPageTo2M(((UINT64)PageDirectory1GEntry-
> >Bits.PageTableBaseAddress)<<30, (UINT64*)
> PageDirectory1GEntry, 0, 0);
> +        Split1GPageTo2M (
> +          (UINT64)PageDirectory1GEntry-
> >Bits.PageTableBaseAddress << 30,
> +          (UINT64 *)PageDirectory1GEntry,
> +          0,
> +          0
> +          );
>          continue;
>        }
>      } else {
>        //
>        // Actually a PDP
>        //
> -      PageUpperDirectoryPointerEntry =
> (PAGE_MAP_AND_DIRECTORY_POINTER*) PageDirectory1GEntry;
> -      PageDirectory2MEntry = (VOID*)
> ((PageUpperDirectoryPointerEntry-
> >Bits.PageTableBaseAddress<<12) & ~PgTableMask);
> +      PageUpperDirectoryPointerEntry =
> +        (PAGE_MAP_AND_DIRECTORY_POINTER
> *)PageDirectory1GEntry;
> +      PageDirectory2MEntry =
> +        (VOID *)(
> +          (PageUpperDirectoryPointerEntry-
> >Bits.PageTableBaseAddress <<
> +           12) & ~PgTableMask
> +          );
>        PageDirectory2MEntry +=
> PDE_OFFSET(PhysicalAddress);
>        if (!PageDirectory2MEntry->Bits.Present) {
>          DEBUG ((
>            DEBUG_ERROR,
>            "%a:%a: bad PDE for Physical=0x%Lx\n",
>            gEfiCallerBaseName,
>            __FUNCTION__,
>            PhysicalAddress
>            ));
>          Status = RETURN_NO_MAPPING;
>          goto Done;
>        }
>        //
>        // If the MustBe1 bit is not a 1, it's not a 2MB
> entry
>        //
>        if (PageDirectory2MEntry->Bits.MustBe1) {
>          //
>          // Valid 2MB page
>          // If we have at least 2MB left to go, we can
> just update this entry
>          //
>          if (!(PhysicalAddress & (BIT21-1)) && Length
> >= BIT21) {
>            SetOrClearCBit (&PageDirectory2MEntry-
> >Uint64, Mode);
>            PhysicalAddress += BIT21;
>            Length -= BIT21;
>          } else {
>            //
>            // We must split up this page into 4K pages
>            //
>            DEBUG ((
>              DEBUG_VERBOSE,
>              "%a:%a: splitting 2MB page for
> Physical=0x%Lx\n",
>              gEfiCallerBaseName,
>              __FUNCTION__,
>              PhysicalAddress
>              ));
> -          Split2MPageTo4K
> (((UINT64)PageDirectory2MEntry-
> >Bits.PageTableBaseAddress) << 21, (UINT64*)
> PageDirectory2MEntry, 0, 0);
> +          Split2MPageTo4K (
> +            (UINT64)PageDirectory2MEntry-
> >Bits.PageTableBaseAddress << 21,
> +            (UINT64 *)PageDirectory2MEntry,
> +            0,
> +            0
> +            );
>            continue;
>          }
>        } else {
> -        PageDirectoryPointerEntry =
> (PAGE_MAP_AND_DIRECTORY_POINTER*) PageDirectory2MEntry;
> -        PageTableEntry = (VOID*)
> (PageDirectoryPointerEntry-
> >Bits.PageTableBaseAddress<<12 & ~PgTableMask);
> +        PageDirectoryPointerEntry =
> +          (PAGE_MAP_AND_DIRECTORY_POINTER
> *)PageDirectory2MEntry;
> +        PageTableEntry =
> +          (VOID *)(
> +            (PageDirectoryPointerEntry-
> >Bits.PageTableBaseAddress <<
> +             12) & ~PgTableMask
> +            );
>          PageTableEntry += PTE_OFFSET(PhysicalAddress);
>          if (!PageTableEntry->Bits.Present) {
>            DEBUG ((
>              DEBUG_ERROR,
>              "%a:%a: bad PTE for Physical=0x%Lx\n",
>              gEfiCallerBaseName,
>              __FUNCTION__,
>              PhysicalAddress
>              ));
>            Status = RETURN_NO_MAPPING;
>            goto Done;
>          }
>          SetOrClearCBit (&PageTableEntry->Uint64,
> Mode);
>          PhysicalAddress += EFI_PAGE_SIZE;
>          Length -= EFI_PAGE_SIZE;
>        }
>      }
>    }
> 
>    //
> @@ -771,66 +815,78 @@ Done:
>    //
>    // Restore page table write protection, if any.
>    //
>    if (IsWpEnabled) {
>      EnableReadOnlyPageWriteProtect ();
>    }
> 
>    return Status;
>  }
> 
>  /**
>    This function clears memory encryption bit for the
> memory region specified by
>    PhysicalAddress and length from the current page
> table context.
> 
>    @param[in]  PhysicalAddress         The physical
> address that is the start
>                                        address of a
> memory region.
>    @param[in]  Length                  The length of
> memory region
>    @param[in]  Flush                   Flush the caches
> before applying the
>                                        encryption mask
> 
> -  @retval RETURN_SUCCESS              The attributes
> were cleared for the memory
> -                                      region.
> +  @retval RETURN_SUCCESS              The attributes
> were cleared for the
> +                                      memory region.
>    @retval RETURN_INVALID_PARAMETER    Number of pages
> is zero.
> -  @retval RETURN_UNSUPPORTED          Setting the
> memory encyrption attribute is
> -                                      not supported
> +  @retval RETURN_UNSUPPORTED          Setting the
> memory encyrption attribute
> +                                      is not supported
>  **/
>  RETURN_STATUS
>  EFIAPI
>  InternalMemEncryptSevSetMemoryDecrypted (
>    IN  PHYSICAL_ADDRESS        Cr3BaseAddress,
>    IN  PHYSICAL_ADDRESS        PhysicalAddress,
>    IN  UINTN                   Length,
>    IN  BOOLEAN                 Flush
>    )
>  {
> 
> -  return SetMemoryEncDec (Cr3BaseAddress,
> PhysicalAddress, Length, ClearCBit, Flush);
> +  return SetMemoryEncDec (
> +           Cr3BaseAddress,
> +           PhysicalAddress,
> +           Length,
> +           ClearCBit,
> +           Flush
> +           );
>  }
> 
>  /**
>    This function sets memory encryption bit for the
> memory region specified by
>    PhysicalAddress and length from the current page
> table context.
> 
> -  @param[in]  PhysicalAddress         The physical
> address that is the start address
> -                                      of a memory
> region.
> +  @param[in]  PhysicalAddress         The physical
> address that is the start
> +                                      address of a
> memory region.
>    @param[in]  Length                  The length of
> memory region
>    @param[in]  Flush                   Flush the caches
> before applying the
>                                        encryption mask
> 
> -  @retval RETURN_SUCCESS              The attributes
> were cleared for the memory
> -                                      region.
> +  @retval RETURN_SUCCESS              The attributes
> were cleared for the
> +                                      memory region.
>    @retval RETURN_INVALID_PARAMETER    Number of pages
> is zero.
> -  @retval RETURN_UNSUPPORTED          Setting the
> memory encyrption attribute is
> -                                      not supported
> +  @retval RETURN_UNSUPPORTED          Setting the
> memory encyrption attribute
> +                                      is not supported
>  **/
>  RETURN_STATUS
>  EFIAPI
>  InternalMemEncryptSevSetMemoryEncrypted (
>    IN  PHYSICAL_ADDRESS        Cr3BaseAddress,
>    IN  PHYSICAL_ADDRESS        PhysicalAddress,
>    IN  UINTN                   Length,
>    IN  BOOLEAN                 Flush
>    )
>  {
> -  return SetMemoryEncDec (Cr3BaseAddress,
> PhysicalAddress, Length, SetCBit, Flush);
> +  return SetMemoryEncDec (
> +           Cr3BaseAddress,
> +           PhysicalAddress,
> +           Length,
> +           SetCBit,
> +           Flush
> +           );
>  }
> --
> 2.14.1.3.gb7cf6e02401b
> 
> 
> _______________________________________________
> edk2-devel mailing list
> edk2-devel@lists.01.org
> https://lists.01.org/mailman/listinfo/edk2-devel


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

* Re: [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (19 preceding siblings ...)
  2018-03-02  0:04 ` [PATCH 20/20] OvmfPkg/AmdSevDxe: decrypt the pages of the initial SMRAM " Laszlo Ersek
@ 2018-03-02  1:16 ` Brijesh Singh
  2018-03-02 11:53   ` Laszlo Ersek
  2018-03-02 15:21 ` Brijesh Singh
  21 siblings, 1 reply; 33+ messages in thread
From: Brijesh Singh @ 2018-03-02  1:16 UTC (permalink / raw)
  To: Laszlo Ersek, edk2-devel-01; +Cc: brijesh.singh, Ard Biesheuvel, Jordan Justen



On 3/1/18 6:03 PM, Laszlo Ersek wrote:
> Repo:   https://github.com/lersek/edk2.git
> Branch: sev_smram_save_state_map
>
> This patch series replaces the following patch from Brijesh:
>
>   [PATCH v2 1/2] OvmfPkg/AmdSevDxe: Clear the C-bit from SMM Saved State
>   http://mid.mail-archive.com/20180228161415.28723-2-brijesh.singh@amd.com
>   https://lists.01.org/pipermail/edk2-devel/2018-February/022016.html
>
> The series modifies four modules under OvmfPkg:
> - MemEncryptSevLib
> - PlatformPei
> - SmmCpuFeaturesLib
> - AmdSevDxe
>
> Patches 01 through 16 are cleanups for these modules, without change in
> functionality. The series is formatted with 20 lines of context, for
> simplifying the review of these patches.
>
> Patches 17 through 20 (one patch per module listed above) implement
> $SUBJECT:
>
> - MemEncryptSevLib gets a new helper function used by the other three
>   modules.
>
> - PlatformPei makes sure that DXE stays out of the page(s) where the
>   initial SMRAM save state map lives.
>
> - SmmCpuFeaturesLib and AmdSevDxe basically do what they did in
>   Brijesh's patch, just better separated, and with minor tweaks.
>
> The series is bisectable.
>
> I regression-tested my usual non-SEV guests (with Brijesh's v2 2/2 patch
> applied on top, from the above-referenced series), which covers i440fx
> (no SMM, X64), q35 (SMM, IA32 and IA32X64), Fedora and Windows, normal
> boot and S3.
>
> I also tried to test the series with SEV guests (again with Brijesh's v2
> 2/2 patch applied on top). Unfortunately, I didn't get good results with
> or without SMM. Without SMM, the guest OS boots to a point, but then it
> gets stuck with the CPU spinning. With SMM, OVMF gets stuck in SMBASE
> relocation.

To boot the SEV guest with SMM support we need this KVM patch, without
this we will get either #UD or some undefined behavior.

https://git.kernel.org/pub/scm/virt/kvm/kvm.git/commit/?id=7607b7174405aec7441ff6c970833c463114040a

It's strange that you are having trouble booting SEV guest without SMM
support. It's possible that we might have some mismatch kernel kvm +
qemu + ovmf patches.
>
> I should mention however that my SEV host setup dates back to November
> 2017, including host kernel, QEMU and guest OS. I suppose all those
> components have seen many changes since, on the respective upstream
> lists. I'll have to work with Brijesh to update my SEV host to the
> latest bits.
>
> Until then, Brijesh, can you please test this series? Thank you!


Sure, I will try the series tomorrow morning. thank you so much for the
cleanup and remaining SMM work.


>
> Cc: Ard Biesheuvel <ard.biesheuvel@linaro.org>
> Cc: Brijesh Singh <brijesh.singh@amd.com>
> Cc: Jordan Justen <jordan.l.justen@intel.com>
>
> Cheers
> Laszlo
>
> Laszlo Ersek (20):
>   OvmfPkg/MemEncryptSevLib: rewrap to 79 characters width
>   OvmfPkg/MemEncryptSevLib: clean up MemEncryptSevIsEnabled() decl
>   OvmfPkg/MemEncryptSevLib: clean up MemEncryptSevClearPageEncMask()
>     decl
>   OvmfPkg/MemEncryptSevLib: clean up MemEncryptSevSetPageEncMask() decl
>   OvmfPkg/MemEncryptSevLib: clean up SetMemoryEncDec() comment block
>   OvmfPkg/MemEncryptSevLib: clean up
>     InternalMemEncryptSevSetMemoryDecrypted() decl
>   OvmfPkg/MemEncryptSevLib: clean up
>     InternalMemEncryptSevSetMemoryEncrypted() decl
>   OvmfPkg/MemEncryptSevLib: sort #includes, and entries in INF file
>     sections
>   OvmfPkg/PlatformPei: sort #includes in "AmdSev.c"
>   OvmfPkg/SmmCpuFeaturesLib: rewrap to 79 columns
>   OvmfPkg/SmmCpuFeaturesLib: upper-case the "static" keyword
>   OvmfPkg/SmmCpuFeaturesLib: sort #includes, and entries in INF file
>     sections
>   OvmfPkg/SmmCpuFeaturesLib: remove unneeded #includes and
>     LibraryClasses
>   OvmfPkg/AmdSevDxe: rewrap to 79 characters width
>   OvmfPkg/AmdSevDxe: sort #includes, and entries in INF file sections
>   OvmfPkg/AmdSevDxe: refresh #includes and LibraryClasses
>   OvmfPkg/MemEncryptSevLib: find pages of initial SMRAM save state map
>   OvmfPkg/PlatformPei: SEV: allocate pages of initial SMRAM save state
>     map
>   OvmfPkg/SmmCpuFeaturesLib: SEV: encrypt+free pages of init. save state
>     map
>   OvmfPkg/AmdSevDxe: decrypt the pages of the initial SMRAM save state
>     map
>
>  OvmfPkg/AmdSevDxe/AmdSevDxe.c                                   |  88 ++-
>  OvmfPkg/AmdSevDxe/AmdSevDxe.inf                                 |  25 +-
>  OvmfPkg/Include/Library/MemEncryptSevLib.h                      |  89 ++-
>  OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf   |  17 +-
>  OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c    |  72 ++-
>  OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c |  66 +-
>  OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c     |  74 ++-
>  OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c        | 172 ++++--
>  OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h        | 137 +++--
>  OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c           | 650 ++++++++++++++++----
>  OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf         |  13 +-
>  OvmfPkg/PlatformPei/AmdSev.c                                    |  36 +-
>  12 files changed, 1067 insertions(+), 372 deletions(-)
>



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

* Re: [PATCH 01/20] OvmfPkg/MemEncryptSevLib: rewrap to 79 characters width
  2018-03-02  0:33   ` Kinney, Michael D
@ 2018-03-02 11:25     ` Laszlo Ersek
  0 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02 11:25 UTC (permalink / raw)
  To: Kinney, Michael D, edk2-devel-01
  Cc: Justen, Jordan L, Brijesh Singh, Ard Biesheuvel

Hi Mike,

On 03/02/18 01:33, Kinney, Michael D wrote:
> Laszlo,
> 
> Sorting #includes looks strange to me.
> 
> We usually include the top level environment include
> first (e.g. <PiPei.h>) and then the libs, protocols,
> ppis, GUIDs grouped together.
> 
> If it is a lib module, the produced libs are listed
> first followed by the consumed libs.

What you describe is the optimal structuring of the includes, and I do
my best to comply with it when I post patches for core modules (MdePkg,
MdeModulePkg, UefiCpuPkg, ...)

However, under OvmfPkg and ArmVirtPkg, I have to disagree strongly. Many
contributors lack either the knowledge or the discipline to follow the
model that you describe. (Enforcing the model as a reviewer is also
quite tedious.) Over time we end up with a mess of #include directives
and LibraryClasses entries, where:

- included library class headers, end entries under [LibraryClasses], do
not match each other (or maybe they do, but it's hard to see because
they are both sort of randomly ordered)

- some headers are included "just to be safe" (they are not kept at a
minimum)

- especially after code removal and code movement, these parts are
littered with dead entries.

Keeping the lists sorted, while not entirely logical, greatly eases
review and maintenance for me. (The sorting also happens to group
Library/, Protocol/, Ppi/, Guid/, IndustryStandard/, Register/, etc
includes "tightly", so at least those aren't intermixed.)

Thanks
Laszlo


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

* Re: [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation
  2018-03-02  1:16 ` [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Brijesh Singh
@ 2018-03-02 11:53   ` Laszlo Ersek
  2018-03-02 13:17     ` Brijesh Singh
  0 siblings, 1 reply; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-02 11:53 UTC (permalink / raw)
  To: Brijesh Singh, edk2-devel-01; +Cc: Ard Biesheuvel, Jordan Justen

On 03/02/18 02:16, Brijesh Singh wrote:
> 
> 
> On 3/1/18 6:03 PM, Laszlo Ersek wrote:

>> I also tried to test the series with SEV guests (again with Brijesh's v2
>> 2/2 patch applied on top). Unfortunately, I didn't get good results with
>> or without SMM. Without SMM, the guest OS boots to a point, but then it
>> gets stuck with the CPU spinning. With SMM, OVMF gets stuck in SMBASE
>> relocation.
> 
> To boot the SEV guest with SMM support we need this KVM patch, without
> this we will get either #UD or some undefined behavior.
> 
> https://git.kernel.org/pub/scm/virt/kvm/kvm.git/commit/?id=7607b7174405aec7441ff6c970833c463114040a

Looks like a very recent commit. What tree (and at what commit) do you
recommend that I build a new host kernel?

> It's strange that you are having trouble booting SEV guest without SMM
> support. It's possible that we might have some mismatch kernel kvm +
> qemu + ovmf patches.

Wait, the details matter: I wrote "the guest OS boots to a point". There
are no problems with the firmware, or the initial OS boot progress. The
issue happens fairly later (but certainly before I reach a login prompt
or similar). Maybe this is nothing new relative to last November; I
don't remember.

>> Until then, Brijesh, can you please test this series? Thank you!
> 
> 
> Sure, I will try the series tomorrow morning. thank you so much for the
> cleanup and remaining SMM work.

Thanks!

Do you have (maybe updated) instructions for setting up the SEV host?
What are the latest bits that are expected to work together?

Thanks!
Laszlo


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

* Re: [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation
  2018-03-02 11:53   ` Laszlo Ersek
@ 2018-03-02 13:17     ` Brijesh Singh
  2018-03-05  9:55       ` Laszlo Ersek
  2018-03-05 14:00       ` Laszlo Ersek
  0 siblings, 2 replies; 33+ messages in thread
From: Brijesh Singh @ 2018-03-02 13:17 UTC (permalink / raw)
  To: Laszlo Ersek, edk2-devel-01; +Cc: brijesh.singh, Ard Biesheuvel, Jordan Justen



On 3/2/18 5:53 AM, Laszlo Ersek wrote:
> On 03/02/18 02:16, Brijesh Singh wrote:
>>
>> On 3/1/18 6:03 PM, Laszlo Ersek wrote:
>>> I also tried to test the series with SEV guests (again with Brijesh's v2
>>> 2/2 patch applied on top). Unfortunately, I didn't get good results with
>>> or without SMM. Without SMM, the guest OS boots to a point, but then it
>>> gets stuck with the CPU spinning. With SMM, OVMF gets stuck in SMBASE
>>> relocation.
>> To boot the SEV guest with SMM support we need this KVM patch, without
>> this we will get either #UD or some undefined behavior.
>>
>> https://git.kernel.org/pub/scm/virt/kvm/kvm.git/commit/?id=7607b7174405aec7441ff6c970833c463114040a
> Looks like a very recent commit. What tree (and at what commit) do you
> recommend that I build a new host kernel?

Yes this is very recent commit and it was developed during SMM work. For
host kernel we need at least 4.16.0-rc1 but since you are going to boot
the SMM enabled BIOS hence I recommend using latest kvm/master

https://git.kernel.org/pub/scm/virt/kvm/kvm.git/

>
>> It's strange that you are having trouble booting SEV guest without SMM
>> support. It's possible that we might have some mismatch kernel kvm +
>> qemu + ovmf patches.
> Wait, the details matter: I wrote "the guest OS boots to a point". There
> are no problems with the firmware, or the initial OS boot progress. The
> issue happens fairly later (but certainly before I reach a login prompt
> or similar). Maybe this is nothing new relative to last November; I
> don't remember.

Ah, my best guess is that userspace program is getting wrong time using
clock_gettime() and hence the bootscripts are waiting on some events
forever .. IIRC, I was getting boot hang sometime back in Oct or Nov and
debugging took me to the kvmclock support for SEV guest. I was doing
everything right in my patches for kvmclock except the first hunk of the
below patch. When kvmclock is available the clock_getttime() uses vdso
and since kvmclock page is shared between HV and Guest hence we needed
to ensure that userspace pgtable have proper C-bit when accessing this
memory range.

https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?h=v4.16-rc3&id=819aeee065e5d1b417ecd633897427c89f3253ec

All the SEV guest got accepted in 4.15, hence for guest kernel you can
use Linux kernel >=4.15

>>> Until then, Brijesh, can you please test this series? Thank you!
>>
>> Sure, I will try the series tomorrow morning. thank you so much for the
>> cleanup and remaining SMM work.
> Thanks!
>
> Do you have (maybe updated) instructions for setting up the SEV host?
> What are the latest bits that are expected to work together?

AMDSEV page https://github.com/AMDESE/AMDSEV contains some instruction
and scripts to boot the SEV guest but its still using the older version
of kernel and qemu. Here is what you need to do:

For host kernel:
- use recent kvm/master
- make sure following kernel config is enabled
  CONFIG_KVM_AMD_SEV
  CONFIG_CRYPTO_DEV_SP_PSP
  CONFIG_AMD_MEM_ENCRYPT
  CONFIG_AMD_MEM_ENCRYPT_ACTIVE_BY_DEFAULT

For guest kernel:
 - you can use host kernel or anything >=4.15
    make sure you have following config enabled in kernel:
      CONFIG_AMD_MEM_ENCRYPT

For qemu:
- v10 patches from this branch
https://github.com/codomania/qemu/tree/v10


> Thanks!
> Laszlo



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

* Re: [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation
  2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
                   ` (20 preceding siblings ...)
  2018-03-02  1:16 ` [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Brijesh Singh
@ 2018-03-02 15:21 ` Brijesh Singh
  2018-03-06 12:59   ` Laszlo Ersek
  21 siblings, 1 reply; 33+ messages in thread
From: Brijesh Singh @ 2018-03-02 15:21 UTC (permalink / raw)
  To: Laszlo Ersek, edk2-devel-01; +Cc: brijesh.singh, Ard Biesheuvel, Jordan Justen



On 03/01/2018 06:03 PM, Laszlo Ersek wrote:
...

> 
> I regression-tested my usual non-SEV guests (with Brijesh's v2 2/2 patch
> applied on top, from the above-referenced series), which covers i440fx
> (no SMM, X64), q35 (SMM, IA32 and IA32X64), Fedora and Windows, normal
> boot and S3.
> 
> I also tried to test the series with SEV guests (again with Brijesh's v2
> 2/2 patch applied on top). Unfortunately, I didn't get good results with
> or without SMM. Without SMM, the guest OS boots to a point, but then it
> gets stuck with the CPU spinning. With SMM, OVMF gets stuck in SMBASE
> relocation.
> 
> I should mention however that my SEV host setup dates back to November
> 2017, including host kernel, QEMU and guest OS. I suppose all those
> components have seen many changes since, on the respective upstream
> lists. I'll have to work with Brijesh to update my SEV host to the
> latest bits.
> 
> Until then, Brijesh, can you please test this series? Thank you!
> 


I tested the series on SEV and non SEV guest (with my v2 2/2 patch 
applied on top of this series). The result is positive,  I am able boot 
both SMM and non SMM enabled BIOS.

Once again, thank you so much for cleanup.

I will submit by v2 2/2 patch after your series is pushed to the tree.

Tested-by: Brijesh Singh <brijesh.singh@amd.com>
Reviewed-by: Brijesh Singh <brijesh.singh@amd.com>


-Brijesh


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

* Re: [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation
  2018-03-02 13:17     ` Brijesh Singh
@ 2018-03-05  9:55       ` Laszlo Ersek
  2018-03-05 14:00       ` Laszlo Ersek
  1 sibling, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-05  9:55 UTC (permalink / raw)
  To: Brijesh Singh, edk2-devel-01; +Cc: Ard Biesheuvel, Jordan Justen

On 03/02/18 14:17, Brijesh Singh wrote:
> 
> 
> On 3/2/18 5:53 AM, Laszlo Ersek wrote:
>> On 03/02/18 02:16, Brijesh Singh wrote:
>>>
>>> On 3/1/18 6:03 PM, Laszlo Ersek wrote:
>>>> I also tried to test the series with SEV guests (again with Brijesh's v2
>>>> 2/2 patch applied on top). Unfortunately, I didn't get good results with
>>>> or without SMM. Without SMM, the guest OS boots to a point, but then it
>>>> gets stuck with the CPU spinning. With SMM, OVMF gets stuck in SMBASE
>>>> relocation.
>>> To boot the SEV guest with SMM support we need this KVM patch, without
>>> this we will get either #UD or some undefined behavior.
>>>
>>> https://git.kernel.org/pub/scm/virt/kvm/kvm.git/commit/?id=7607b7174405aec7441ff6c970833c463114040a
>> Looks like a very recent commit. What tree (and at what commit) do you
>> recommend that I build a new host kernel?
> 
> Yes this is very recent commit and it was developed during SMM work. For
> host kernel we need at least 4.16.0-rc1 but since you are going to boot
> the SMM enabled BIOS hence I recommend using latest kvm/master
> 
> https://git.kernel.org/pub/scm/virt/kvm/kvm.git/
> 
>>
>>> It's strange that you are having trouble booting SEV guest without SMM
>>> support. It's possible that we might have some mismatch kernel kvm +
>>> qemu + ovmf patches.
>> Wait, the details matter: I wrote "the guest OS boots to a point". There
>> are no problems with the firmware, or the initial OS boot progress. The
>> issue happens fairly later (but certainly before I reach a login prompt
>> or similar). Maybe this is nothing new relative to last November; I
>> don't remember.
> 
> Ah, my best guess is that userspace program is getting wrong time using
> clock_gettime() and hence the bootscripts are waiting on some events
> forever .. IIRC, I was getting boot hang sometime back in Oct or Nov and
> debugging took me to the kvmclock support for SEV guest. I was doing
> everything right in my patches for kvmclock except the first hunk of the
> below patch. When kvmclock is available the clock_getttime() uses vdso
> and since kvmclock page is shared between HV and Guest hence we needed
> to ensure that userspace pgtable have proper C-bit when accessing this
> memory range.
> 
> https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?h=v4.16-rc3&id=819aeee065e5d1b417ecd633897427c89f3253ec
> 
> All the SEV guest got accepted in 4.15, hence for guest kernel you can
> use Linux kernel >=4.15
> 
>>>> Until then, Brijesh, can you please test this series? Thank you!
>>>
>>> Sure, I will try the series tomorrow morning. thank you so much for the
>>> cleanup and remaining SMM work.
>> Thanks!
>>
>> Do you have (maybe updated) instructions for setting up the SEV host?
>> What are the latest bits that are expected to work together?
> 
> AMDSEV page https://github.com/AMDESE/AMDSEV contains some instruction
> and scripts to boot the SEV guest but its still using the older version
> of kernel and qemu. Here is what you need to do:
> 
> For host kernel:
> - use recent kvm/master
> - make sure following kernel config is enabled
>   CONFIG_KVM_AMD_SEV
>   CONFIG_CRYPTO_DEV_SP_PSP
>   CONFIG_AMD_MEM_ENCRYPT
>   CONFIG_AMD_MEM_ENCRYPT_ACTIVE_BY_DEFAULT
> 
> For guest kernel:
>  - you can use host kernel or anything >=4.15
>     make sure you have following config enabled in kernel:
>       CONFIG_AMD_MEM_ENCRYPT
> 
> For qemu:
> - v10 patches from this branch
> https://github.com/codomania/qemu/tree/v10

Great, I'll work on updating all the bits and I'll report back.

Thanks!
Laszlo


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

* Re: [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation
  2018-03-02 13:17     ` Brijesh Singh
  2018-03-05  9:55       ` Laszlo Ersek
@ 2018-03-05 14:00       ` Laszlo Ersek
  2018-03-05 14:44         ` Brijesh Singh
  1 sibling, 1 reply; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-05 14:00 UTC (permalink / raw)
  To: Brijesh Singh, edk2-devel-01; +Cc: Ard Biesheuvel, Jordan Justen

On 03/02/18 14:17, Brijesh Singh wrote:
> On 3/2/18 5:53 AM, Laszlo Ersek wrote:

>> Do you have (maybe updated) instructions for setting up the SEV host?
>> What are the latest bits that are expected to work together?

> For host kernel:
> - use recent kvm/master
> - make sure following kernel config is enabled
>   CONFIG_KVM_AMD_SEV
>   CONFIG_CRYPTO_DEV_SP_PSP
>   CONFIG_AMD_MEM_ENCRYPT
>   CONFIG_AMD_MEM_ENCRYPT_ACTIVE_BY_DEFAULT
> 
> For guest kernel:
>  - you can use host kernel or anything >=4.15
>     make sure you have following config enabled in kernel:
>       CONFIG_AMD_MEM_ENCRYPT
> 
> For qemu:
> - v10 patches from this branch
> https://github.com/codomania/qemu/tree/v10

QEMU exits with the following error for me:

2018-03-05T13:40:12.478835Z qemu-system-x86_64: sev_ram_block_added: failed to register region (0x7f3df3e00000+0x200000000)
2018-03-05T13:40:12.489183Z qemu-system-x86_64: sev_ram_block_added: failed to register region (0x7f3ffaa00000+0x37c000)
2018-03-05T13:40:12.497580Z qemu-system-x86_64: sev_ram_block_added: failed to register region (0x7f3ffa800000+0x20000)
2018-03-05T13:40:12.504485Z qemu-system-x86_64: sev_launch_update_data: LAUNCH_UPDATE ret=-12 fw_error=0 ''
2018-03-05T13:40:12.504493Z qemu-system-x86_64: failed to encrypt pflash rom

Here's my full QEMU command line (started by libvirt) -- this command line does not restrict pflash access to guest code that runs in SMM, and correspondingly, the OVMF build lacks SMM_REQUIRE:

/opt/qemu-installed/bin/qemu-system-x86_64 \
  -name guest=from-brijesh,debug-threads=on \
  -S \
  -object secret,id=masterKey0,format=raw,file=/var/lib/libvirt/qemu/domain-4-from-brijesh/master-key.aes \
  -machine pc-q35-2.10,accel=kvm,usb=off,smm=on,dump-guest-core=off \
  -cpu host \
  -drive file=/home/virt-images/OVMF_CODE.4m.fd,if=pflash,format=raw,unit=0,readonly=on \
  -drive file=/var/lib/libvirt/qemu/nvram/from-brijesh_VARS.fd,if=pflash,format=raw,unit=1 \
  -m 8192 \
  -realtime mlock=off \
  -smp 1,sockets=1,cores=1,threads=1 \
  -uuid e2373f13-f481-4008-88d0-d61fa9da16fe \
  -no-user-config \
  -nodefaults \
  -chardev socket,id=charmonitor,path=/var/lib/libvirt/qemu/domain-4-from-brijesh/monitor.sock,server,nowait \
  -mon chardev=charmonitor,id=monitor,mode=control \
  -rtc base=utc \
  -no-shutdown \
  -boot strict=on \
  -device pcie-root-port,port=0x10,chassis=1,id=pci.1,bus=pcie.0,multifunction=on,addr=0x2 \
  -device pcie-root-port,port=0x11,chassis=2,id=pci.2,bus=pcie.0,addr=0x2.0x1 \
  -device pcie-root-port,port=0x12,chassis=3,id=pci.3,bus=pcie.0,addr=0x2.0x2 \
  -device pcie-root-port,port=0x13,chassis=4,id=pci.4,bus=pcie.0,addr=0x2.0x3 \
  -device nec-usb-xhci,id=usb,bus=pci.1,addr=0x0 \
  -device virtio-scsi-pci,iommu_platform=on,ats=on,id=scsi0,bus=pci.3,addr=0x0 \
  -drive file=/var/lib/libvirt/images/rhel-7-server.qcow2,format=qcow2,if=none,id=drive-scsi0-0-0-0,cache=writeback,discard=unmap,werror=enospc \
  -device scsi-hd,bus=scsi0.0,channel=0,scsi-id=0,lun=0,drive=drive-scsi0-0-0-0,id=scsi0-0-0-0,bootindex=1 \
  -netdev tap,fd=26,id=hostnet0,vhost=on,vhostfd=28 \
  -device virtio-net-pci,netdev=hostnet0,id=net0,mac=52:54:00:65:f7:fb,bus=pci.4,addr=0x0,rombar=0 \
  -chardev pty,id=charserial0 \
  -device isa-serial,chardev=charserial0,id=serial0 \
  -device usb-tablet,id=input2,bus=usb.0,port=1 \
  -spice port=5900,addr=127.0.0.1,disable-ticketing,seamless-migration=on \
  -device cirrus-vga,id=video0,bus=pcie.0,addr=0x1 \
  -device virtio-balloon-pci,id=balloon0,bus=pci.2,addr=0x0 \
  -global isa-debugcon.iobase=0x402 \
  -debugcon file:/tmp/from-brijesh.log \
  -fw_cfg name=opt/ovmf/PcdResizeXterm,string=y \
  -s \
  -object sev-guest,id=sev0,policy=0x0,cbitpos=47,reduced-phys-bits=5 \
  -machine memory-encryption=sev0 \
  -msg timestamp=on

Thanks,
Laszlo


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

* Re: [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation
  2018-03-05 14:00       ` Laszlo Ersek
@ 2018-03-05 14:44         ` Brijesh Singh
  2018-03-05 14:47           ` Brijesh Singh
  2018-03-05 21:06           ` Laszlo Ersek
  0 siblings, 2 replies; 33+ messages in thread
From: Brijesh Singh @ 2018-03-05 14:44 UTC (permalink / raw)
  To: Laszlo Ersek, edk2-devel-01; +Cc: brijesh.singh, Ard Biesheuvel, Jordan Justen

Hi Laszlo,



On 03/05/2018 08:00 AM, Laszlo Ersek wrote:
> On 03/02/18 14:17, Brijesh Singh wrote:
>> On 3/2/18 5:53 AM, Laszlo Ersek wrote:
> 
>>> Do you have (maybe updated) instructions for setting up the SEV host?
>>> What are the latest bits that are expected to work together?
> 
>> For host kernel:
>> - use recent kvm/master
>> - make sure following kernel config is enabled
>>    CONFIG_KVM_AMD_SEV
>>    CONFIG_CRYPTO_DEV_SP_PSP
>>    CONFIG_AMD_MEM_ENCRYPT
>>    CONFIG_AMD_MEM_ENCRYPT_ACTIVE_BY_DEFAULT
>>
>> For guest kernel:
>>   - you can use host kernel or anything >=4.15
>>      make sure you have following config enabled in kernel:
>>        CONFIG_AMD_MEM_ENCRYPT
>>
>> For qemu:
>> - v10 patches from this branch
>> https://github.com/codomania/qemu/tree/v10
> 
> QEMU exits with the following error for me:
> 
> 2018-03-05T13:40:12.478835Z qemu-system-x86_64: sev_ram_block_added: failed to register region (0x7f3df3e00000+0x200000000)
> 2018-03-05T13:40:12.489183Z qemu-system-x86_64: sev_ram_block_added: failed to register region (0x7f3ffaa00000+0x37c000)
> 2018-03-05T13:40:12.497580Z qemu-system-x86_64: sev_ram_block_added: failed to register region (0x7f3ffa800000+0x20000)
> 2018-03-05T13:40:12.504485Z qemu-system-x86_64: sev_launch_update_data: LAUNCH_UPDATE ret=-12 fw_error=0 ''
> 2018-03-05T13:40:12.504493Z qemu-system-x86_64: failed to encrypt pflash rom
> 
> Here's my full QEMU command line (started by libvirt) -- this command line does not restrict pflash access to guest code that runs in SMM, and correspondingly, the OVMF build lacks SMM_REQUIRE:
> 

Are you launching guest as a normal users or root ? If you are launching 
guest as normal user then please make sure you have increased the 'max 
locked memory' limit. The register region function will try to pin the 
memory, while doing so we check the limit and if requested size is 
greater than ulimit then we fail.


# ulimit -a
core file size          (blocks, -c) unlimited
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 966418
max locked memory       (kbytes, -l) 10240000
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 966418
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

If QEMU command is still failing for you then can you please share your 
kernel dmesg. thanks


> /opt/qemu-installed/bin/qemu-system-x86_64 \
>    -name guest=from-brijesh,debug-threads=on \
>    -S \
>    -object secret,id=masterKey0,format=raw,file=/var/lib/libvirt/qemu/domain-4-from-brijesh/master-key.aes \
>    -machine pc-q35-2.10,accel=kvm,usb=off,smm=on,dump-guest-core=off \
>    -cpu host \
>    -drive file=/home/virt-images/OVMF_CODE.4m.fd,if=pflash,format=raw,unit=0,readonly=on \
>    -drive file=/var/lib/libvirt/qemu/nvram/from-brijesh_VARS.fd,if=pflash,format=raw,unit=1 \
>    -m 8192 \
>    -realtime mlock=off \
>    -smp 1,sockets=1,cores=1,threads=1 \
>    -uuid e2373f13-f481-4008-88d0-d61fa9da16fe \
>    -no-user-config \
>    -nodefaults \
>    -chardev socket,id=charmonitor,path=/var/lib/libvirt/qemu/domain-4-from-brijesh/monitor.sock,server,nowait \
>    -mon chardev=charmonitor,id=monitor,mode=control \
>    -rtc base=utc \
>    -no-shutdown \
>    -boot strict=on \
>    -device pcie-root-port,port=0x10,chassis=1,id=pci.1,bus=pcie.0,multifunction=on,addr=0x2 \
>    -device pcie-root-port,port=0x11,chassis=2,id=pci.2,bus=pcie.0,addr=0x2.0x1 \
>    -device pcie-root-port,port=0x12,chassis=3,id=pci.3,bus=pcie.0,addr=0x2.0x2 \
>    -device pcie-root-port,port=0x13,chassis=4,id=pci.4,bus=pcie.0,addr=0x2.0x3 \
>    -device nec-usb-xhci,id=usb,bus=pci.1,addr=0x0 \
>    -device virtio-scsi-pci,iommu_platform=on,ats=on,id=scsi0,bus=pci.3,addr=0x0 \
>    -drive file=/var/lib/libvirt/images/rhel-7-server.qcow2,format=qcow2,if=none,id=drive-scsi0-0-0-0,cache=writeback,discard=unmap,werror=enospc \
>    -device scsi-hd,bus=scsi0.0,channel=0,scsi-id=0,lun=0,drive=drive-scsi0-0-0-0,id=scsi0-0-0-0,bootindex=1 \
>    -netdev tap,fd=26,id=hostnet0,vhost=on,vhostfd=28 \
>    -device virtio-net-pci,netdev=hostnet0,id=net0,mac=52:54:00:65:f7:fb,bus=pci.4,addr=0x0,rombar=0 \
>    -chardev pty,id=charserial0 \
>    -device isa-serial,chardev=charserial0,id=serial0 \
>    -device usb-tablet,id=input2,bus=usb.0,port=1 \
>    -spice port=5900,addr=127.0.0.1,disable-ticketing,seamless-migration=on \
>    -device cirrus-vga,id=video0,bus=pcie.0,addr=0x1 \
>    -device virtio-balloon-pci,id=balloon0,bus=pci.2,addr=0x0 \
>    -global isa-debugcon.iobase=0x402 \
>    -debugcon file:/tmp/from-brijesh.log \
>    -fw_cfg name=opt/ovmf/PcdResizeXterm,string=y \
>    -s \
>    -object sev-guest,id=sev0,policy=0x0,cbitpos=47,reduced-phys-bits=5 \
>    -machine memory-encryption=sev0 \
>    -msg timestamp=on
> 
> Thanks,
> Laszlo
> 


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

* Re: [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation
  2018-03-05 14:44         ` Brijesh Singh
@ 2018-03-05 14:47           ` Brijesh Singh
  2018-03-05 21:06           ` Laszlo Ersek
  1 sibling, 0 replies; 33+ messages in thread
From: Brijesh Singh @ 2018-03-05 14:47 UTC (permalink / raw)
  To: Laszlo Ersek, edk2-devel-01; +Cc: brijesh.singh, Ard Biesheuvel, Jordan Justen

One more comment.


On 03/05/2018 08:44 AM, Brijesh Singh wrote: >> \
>>    -device 
>> scsi-hd,bus=scsi0.0,channel=0,scsi-id=0,lun=0,drive=drive-scsi0-0-0-0,id=scsi0-0-0-0,bootindex=1 
>> \
>>    -netdev tap,fd=26,id=hostnet0,vhost=on,vhostfd=28 \
>>    -device 
>> virtio-net-pci,netdev=hostnet0,id=net0,mac=52:54:00:65:f7:fb,bus=pci.4,addr=0x0,rombar=0 
>> \

Please add iommu_platform=on,ats=on argument in virtio network. In order 
the SEV guest to work with virtio we need to use iommu_platform=on.


>>    -chardev pty,id=charserial0 \
>>    -device isa-serial,chardev=charserial0,id=serial0 \
>>    -device usb-tablet,id=input2,bus=usb.0,port=1 \
>>    -spice 
>> port=5900,addr=127.0.0.1,disable-ticketing,seamless-migration=on \
>>    -device cirrus-vga,id=video0,bus=pcie.0,addr=0x1 \
>>    -device virtio-balloon-pci,id=balloon0,bus=pci.2,addr=0x0 \
>>    -global isa-debugcon.iobase=0x402 \
>>    -debugcon file:/tmp/from-brijesh.log \
>>    -fw_cfg name=opt/ovmf/PcdResizeXterm,string=y \
>>    -s \
>>    -object sev-guest,id=sev0,policy=0x0,cbitpos=47,reduced-phys-bits=5 \
>>    -machine memory-encryption=sev0 \
>>    -msg timestamp=on
>>
>> Thanks,
>> Laszlo
>>


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

* Re: [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation
  2018-03-05 14:44         ` Brijesh Singh
  2018-03-05 14:47           ` Brijesh Singh
@ 2018-03-05 21:06           ` Laszlo Ersek
  1 sibling, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-05 21:06 UTC (permalink / raw)
  To: Brijesh Singh, edk2-devel-01; +Cc: Ard Biesheuvel, Jordan Justen

On 03/05/18 15:44, Brijesh Singh wrote:
> On 03/05/2018 08:00 AM, Laszlo Ersek wrote:

>> QEMU exits with the following error for me:
>>
>> 2018-03-05T13:40:12.478835Z qemu-system-x86_64: sev_ram_block_added:
>> failed to register region (0x7f3df3e00000+0x200000000)
>> 2018-03-05T13:40:12.489183Z qemu-system-x86_64: sev_ram_block_added:
>> failed to register region (0x7f3ffaa00000+0x37c000)
>> 2018-03-05T13:40:12.497580Z qemu-system-x86_64: sev_ram_block_added:
>> failed to register region (0x7f3ffa800000+0x20000)
>> 2018-03-05T13:40:12.504485Z qemu-system-x86_64:
>> sev_launch_update_data: LAUNCH_UPDATE ret=-12 fw_error=0 ''
>> 2018-03-05T13:40:12.504493Z qemu-system-x86_64: failed to encrypt
>> pflash rom
>>
>> Here's my full QEMU command line (started by libvirt) -- this command
>> line does not restrict pflash access to guest code that runs in SMM,
>> and correspondingly, the OVMF build lacks SMM_REQUIRE:
>>
> 
> Are you launching guest as a normal users or root ? If you are launching
> guest as normal user then please make sure you have increased the 'max
> locked memory' limit. The register region function will try to pin the
> memory, while doing so we check the limit and if requested size is
> greater than ulimit then we fail.
> 
> 
> # ulimit -a
> core file size          (blocks, -c) unlimited
> data seg size           (kbytes, -d) unlimited
> scheduling priority             (-e) 0
> file size               (blocks, -f) unlimited
> pending signals                 (-i) 966418
> max locked memory       (kbytes, -l) 10240000
> max memory size         (kbytes, -m) unlimited
> open files                      (-n) 1024
> pipe size            (512 bytes, -p) 8
> POSIX message queues     (bytes, -q) 819200
> real-time priority              (-r) 0
> stack size              (kbytes, -s) 8192
> cpu time               (seconds, -t) unlimited
> max user processes              (-u) 966418
> virtual memory          (kbytes, -v) unlimited
> file locks                      (-x) unlimited

Good catch! Libvirtd starts the QEMU process with UID=qemu, but the
restriction doesn't come from there.

Instead, it seems like the systemd default for "max locked memory" is
64KB on RHEL-7 anyway. I raised it by setting

  DefaultLimitMEMLOCK=infinity

in "/etc/systemd/system.conf".

(The documentation is at:
- <https://www.freedesktop.org/software/systemd/man/systemd.exec.html>,
-
<https://www.freedesktop.org/software/systemd/man/systemd-system.conf.html>.)

Following your other email, I've now also added
"iommu_platform=on,ats=on" to virtio-net-pci, not just virtio-scsi-pci.

This got a lot farther: the TianoCore splash screen was dispalyed, but
then it got stuck.

Looking more at the libvirt-generated command line, I figured maybe
"vhost" should be disabled for virtio-net (so that the device
implementation would run from QEMU userspace, not in the host kernel).
Thus, ultimately I added

    <interface type='network'>
      <driver name='qemu' iommu='on' ats='on'/>
              ^^^^^^^^^^^
    </interface>

documented at
<https://libvirt.org/formatdomain.html#elementsDriverBackendOptions>.

With these settings, the guest boots & works fine for me! I tested the
SEV guest with 4 VCPUs, both with and without SMM. (I used the same
kernel in the guest as on the host -- you wrote CONFIG_AMD_MEM_ENCRYPT
for the guest, and the host requirements imply that.)

I'm attaching the full domain XML for reference.

Thanks!
Laszlo


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

* Re: [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation
  2018-03-02 15:21 ` Brijesh Singh
@ 2018-03-06 12:59   ` Laszlo Ersek
  0 siblings, 0 replies; 33+ messages in thread
From: Laszlo Ersek @ 2018-03-06 12:59 UTC (permalink / raw)
  To: Brijesh Singh, edk2-devel-01; +Cc: Jordan Justen, Ard Biesheuvel

On 03/02/18 16:21, Brijesh Singh wrote:
> 
> 
> On 03/01/2018 06:03 PM, Laszlo Ersek wrote:
> ...
> 
>>
>> I regression-tested my usual non-SEV guests (with Brijesh's v2 2/2 patch
>> applied on top, from the above-referenced series), which covers i440fx
>> (no SMM, X64), q35 (SMM, IA32 and IA32X64), Fedora and Windows, normal
>> boot and S3.
>>
>> I also tried to test the series with SEV guests (again with Brijesh's v2
>> 2/2 patch applied on top). Unfortunately, I didn't get good results with
>> or without SMM. Without SMM, the guest OS boots to a point, but then it
>> gets stuck with the CPU spinning. With SMM, OVMF gets stuck in SMBASE
>> relocation.
>>
>> I should mention however that my SEV host setup dates back to November
>> 2017, including host kernel, QEMU and guest OS. I suppose all those
>> components have seen many changes since, on the respective upstream
>> lists. I'll have to work with Brijesh to update my SEV host to the
>> latest bits.
>>
>> Until then, Brijesh, can you please test this series? Thank you!
>>
> 
> 
> I tested the series on SEV and non SEV guest (with my v2 2/2 patch
> applied on top of this series). The result is positive,  I am able boot
> both SMM and non SMM enabled BIOS.
> 
> Once again, thank you so much for cleanup.
> 
> I will submit by v2 2/2 patch after your series is pushed to the tree.
> 
> Tested-by: Brijesh Singh <brijesh.singh@amd.com>
> Reviewed-by: Brijesh Singh <brijesh.singh@amd.com>

Series pushed: 66f2329446db..5e2e5647b9fb.

Thanks!
Laszlo


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

end of thread, other threads:[~2018-03-06 12:53 UTC | newest]

Thread overview: 33+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2018-03-02  0:03 [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Laszlo Ersek
2018-03-02  0:03 ` [PATCH 01/20] OvmfPkg/MemEncryptSevLib: rewrap to 79 characters width Laszlo Ersek
2018-03-02  0:33   ` Kinney, Michael D
2018-03-02 11:25     ` Laszlo Ersek
2018-03-02  0:03 ` [PATCH 02/20] OvmfPkg/MemEncryptSevLib: clean up MemEncryptSevIsEnabled() decl Laszlo Ersek
2018-03-02  0:03 ` [PATCH 03/20] OvmfPkg/MemEncryptSevLib: clean up MemEncryptSevClearPageEncMask() decl Laszlo Ersek
2018-03-02  0:03 ` [PATCH 04/20] OvmfPkg/MemEncryptSevLib: clean up MemEncryptSevSetPageEncMask() decl Laszlo Ersek
2018-03-02  0:03 ` [PATCH 05/20] OvmfPkg/MemEncryptSevLib: clean up SetMemoryEncDec() comment block Laszlo Ersek
2018-03-02  0:03 ` [PATCH 06/20] OvmfPkg/MemEncryptSevLib: clean up InternalMemEncryptSevSetMemoryDecrypted() decl Laszlo Ersek
2018-03-02  0:03 ` [PATCH 07/20] OvmfPkg/MemEncryptSevLib: clean up InternalMemEncryptSevSetMemoryEncrypted() decl Laszlo Ersek
2018-03-02  0:03 ` [PATCH 08/20] OvmfPkg/MemEncryptSevLib: sort #includes, and entries in INF file sections Laszlo Ersek
2018-03-02  0:03 ` [PATCH 09/20] OvmfPkg/PlatformPei: sort #includes in "AmdSev.c" Laszlo Ersek
2018-03-02  0:03 ` [PATCH 10/20] OvmfPkg/SmmCpuFeaturesLib: rewrap to 79 columns Laszlo Ersek
2018-03-02  0:03 ` [PATCH 11/20] OvmfPkg/SmmCpuFeaturesLib: upper-case the "static" keyword Laszlo Ersek
2018-03-02  0:04 ` [PATCH 12/20] OvmfPkg/SmmCpuFeaturesLib: sort #includes, and entries in INF file sections Laszlo Ersek
2018-03-02  0:04 ` [PATCH 13/20] OvmfPkg/SmmCpuFeaturesLib: remove unneeded #includes and LibraryClasses Laszlo Ersek
2018-03-02  0:04 ` [PATCH 14/20] OvmfPkg/AmdSevDxe: rewrap to 79 characters width Laszlo Ersek
2018-03-02  0:04 ` [PATCH 15/20] OvmfPkg/AmdSevDxe: sort #includes, and entries in INF file sections Laszlo Ersek
2018-03-02  0:04 ` [PATCH 16/20] OvmfPkg/AmdSevDxe: refresh #includes and LibraryClasses Laszlo Ersek
2018-03-02  0:04 ` [PATCH 17/20] OvmfPkg/MemEncryptSevLib: find pages of initial SMRAM save state map Laszlo Ersek
2018-03-02  0:04 ` [PATCH 18/20] OvmfPkg/PlatformPei: SEV: allocate " Laszlo Ersek
2018-03-02  0:04 ` [PATCH 19/20] OvmfPkg/SmmCpuFeaturesLib: SEV: encrypt+free pages of init. " Laszlo Ersek
2018-03-02  0:04 ` [PATCH 20/20] OvmfPkg/AmdSevDxe: decrypt the pages of the initial SMRAM " Laszlo Ersek
2018-03-02  1:16 ` [PATCH 00/20] OvmfPkg: SEV: decrypt the initial SMRAM save state map for SMBASE relocation Brijesh Singh
2018-03-02 11:53   ` Laszlo Ersek
2018-03-02 13:17     ` Brijesh Singh
2018-03-05  9:55       ` Laszlo Ersek
2018-03-05 14:00       ` Laszlo Ersek
2018-03-05 14:44         ` Brijesh Singh
2018-03-05 14:47           ` Brijesh Singh
2018-03-05 21:06           ` Laszlo Ersek
2018-03-02 15:21 ` Brijesh Singh
2018-03-06 12:59   ` Laszlo Ersek

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