* [RFC v4 01/13] UefiCpuPkg: Define AMD Memory Encryption specific CPUID and MSR
2017-05-10 22:09 [RFC v4 00/13] x86: Secure Encrypted Virtualization (AMD) Brijesh Singh
@ 2017-05-10 22:09 ` Brijesh Singh
2017-05-11 0:30 ` Fan, Jeff
2017-05-10 22:09 ` [RFC v4 02/13] OvmfPkg/ResetVector: Set C-bit when building initial page table Brijesh Singh
` (11 subsequent siblings)
12 siblings, 1 reply; 42+ messages in thread
From: Brijesh Singh @ 2017-05-10 22:09 UTC (permalink / raw)
To: edk2-devel
Cc: Thomas.Lendacky, leo.duran, Brijesh Singh, Jordan Justen,
Laszlo Ersek, Jeff Fan, Liming Gao
The patch defines AMD's Memory Encryption Information CPUID leaf and SEV
status MSR. The complete description for CPUID leaf is available in APM
volume 2, Section 15.34.
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Cc: Jeff Fan <jeff.fan@intel.com>
Cc: Liming Gao <liming.gao@intel.com>
Cc: Leo Duran <leo.duran@amd.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
---
UefiCpuPkg/Include/Register/Amd/Cpuid.h | 162 ++++++++++++++++++++
UefiCpuPkg/Include/Register/Amd/Fam17Msr.h | 62 ++++++++
UefiCpuPkg/Include/Register/Amd/Msr.h | 29 ++++
3 files changed, 253 insertions(+)
diff --git a/UefiCpuPkg/Include/Register/Amd/Cpuid.h b/UefiCpuPkg/Include/Register/Amd/Cpuid.h
new file mode 100644
index 000000000000..5cd42667dc46
--- /dev/null
+++ b/UefiCpuPkg/Include/Register/Amd/Cpuid.h
@@ -0,0 +1,162 @@
+/** @file
+ CPUID leaf definitions.
+
+ Provides defines for CPUID leaf indexes. Data structures are provided for
+ registers returned by a CPUID leaf that contain one or more bit fields.
+ If a register returned is a single 32-bit value, then a data structure is
+ not provided for that register.
+
+ 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.
+
+ @par Specification Reference:
+ AMD64 Architecture Programming Manaul volume 2, March 2017, Sections 15.34
+
+**/
+
+#ifndef __AMD_CPUID_H__
+#define __AMD_CPUID_H__
+
+/**
+
+ Memory Encryption Information
+
+ @param EAX CPUID_MEMORY_ENCRYPTION_INFO (0x8000001F)
+
+ @retval EAX Returns the memory encryption feature support status.
+ @retval EBX If memory encryption feature is present then return
+ the page table bit number used to enable memory encryption support
+ and reducing of physical address space in bits.
+ @retval ECX Returns number of encrypted guest supported simultaneosuly.
+ @retval EDX Returns minimum SEV enabled and SEV disbled ASID..
+
+ <b>Example usage</b>
+ @code
+ UINT32 Eax;
+ UINT32 Ebx;
+ UINT32 Ecx;
+ UINT32 Edx;
+
+ AsmCpuid (CPUID_MEMORY_ENCRYPTION_INFO, &Eax, &Ebx, &Ecx, &Edx);
+ @endcode
+**/
+
+#define CPUID_MEMORY_ENCRYPTION_INFO 0x8000001F
+
+/**
+ CPUID Memory Encryption support information EAX for CPUID leaf
+ #CPUID_MEMORY_ENCRYPTION_INFO.
+**/
+typedef union {
+ ///
+ /// Individual bit fields
+ ///
+ struct {
+ ///
+ /// [Bit 0] Secure Memory Encryption (Sme) Support
+ ///
+ UINT32 SmeBit:1;
+
+ ///
+ /// [Bit 1] Secure Encrypted Virtualization (Sev) Support
+ ///
+ UINT32 SevBit:1;
+
+ ///
+ /// [Bit 2] Page flush MSR support
+ ///
+ UINT32 PageFlushMsrBit:1;
+
+ ///
+ /// [Bit 3] Encrypted state support
+ ///
+ UINT32 SevEsBit:1;
+
+ ///
+ /// [Bit 4:31] Reserved
+ ///
+ UINT32 ReservedBits:28;
+ } Bits;
+ ///
+ /// All bit fields as a 32-bit value
+ ///
+ UINT32 Uint32;
+} CPUID_MEMORY_ENCRYPTION_INFO_EAX;
+
+/**
+ CPUID Memory Encryption support information EBX for CPUID leaf
+ #CPUID_MEMORY_ENCRYPTION_INFO.
+**/
+typedef union {
+ ///
+ /// Individual bit fields
+ ///
+ struct {
+ ///
+ /// [Bit 0:5] Page table bit number used to enable memory encryption
+ ///
+ UINT32 PtePosBits:6;
+
+ ///
+ /// [Bit 6:11] Reduction of system physical address space bits when memory encryption is enabled
+ ///
+ UINT32 ReducedPhysBits:5;
+
+ ///
+ /// [Bit 12:31] Reserved
+ ///
+ UINT32 ReservedBits:21;
+ } Bits;
+ ///
+ /// All bit fields as a 32-bit value
+ ///
+ UINT32 Uint32;
+} CPUID_MEMORY_ENCRYPTION_INFO_EBX;
+
+/**
+ CPUID Memory Encryption support information ECX for CPUID leaf
+ #CPUID_MEMORY_ENCRYPTION_INFO.
+**/
+typedef union {
+ ///
+ /// Individual bit fields
+ ///
+ struct {
+ ///
+ /// [Bit 0:31] Number of encrypted guest supported simultaneously
+ ///
+ UINT32 NumGuests;
+ } Bits;
+ ///
+ /// All bit fields as a 32-bit value
+ ///
+ UINT32 Uint32;
+} CPUID_MEMORY_ENCRYPTION_INFO_ECX;
+
+/**
+ CPUID Memory Encryption support information EDX for CPUID leaf
+ #CPUID_MEMORY_ENCRYPTION_INFO.
+**/
+typedef union {
+ ///
+ /// Individual bit fields
+ ///
+ struct {
+ ///
+ /// [Bit 0:31] Minimum SEV enabled, SEV-ES disabled ASID
+ ///
+ UINT32 MinAsid;
+ } Bits;
+ ///
+ /// All bit fields as a 32-bit value
+ ///
+ UINT32 Uint32;
+} CPUID_MEMORY_ENCRYPTION_INFO_EDX;
+
+#endif
diff --git a/UefiCpuPkg/Include/Register/Amd/Fam17Msr.h b/UefiCpuPkg/Include/Register/Amd/Fam17Msr.h
new file mode 100644
index 000000000000..2c5d9738fae8
--- /dev/null
+++ b/UefiCpuPkg/Include/Register/Amd/Fam17Msr.h
@@ -0,0 +1,62 @@
+/** @file
+ MSR Definitions.
+
+ Provides defines for Machine Specific Registers(MSR) indexes. Data structures
+ are provided for MSRs that contain one or more bit fields. If the MSR value
+ returned is a single 32-bit or 64-bit value, then a data structure is not
+ provided for that MSR.
+
+ 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.
+
+ @par Specification Reference:
+ AMD64 Architecture Programming Manaul volume 2, March 2017, Sections 15.34
+
+**/
+
+#ifndef __FAM17_MSR_H
+#define __FAM17_MSR_H
+
+/**
+ Secure Encrypted Virtualization (SEV) status register
+
+**/
+#define MSR_SEV_STATUS 0xc0010131
+
+/**
+ MSR information returned for #MSR_SEV_STATUS
+**/
+typedef union {
+ ///
+ /// Individual bit fields
+ ///
+ struct {
+ ///
+ /// [Bit 0] Secure Encrypted Virtualization (Sev) is enabled
+ ///
+ UINT32 SevBit:1;
+
+ ///
+ /// [Bit 1] Secure Encrypted Virtualization Encrypted State (SevEs) is enabled
+ ///
+ UINT32 SevEsBit:1;
+
+ UINT32 Reserved:30;
+ } Bits;
+ ///
+ /// All bit fields as a 32-bit value
+ ///
+ UINT32 Uint32;
+ ///
+ /// All bit fields as a 64-bit value
+ ///
+ UINT64 Uint64;
+} MSR_SEV_STATUS_REGISTER;
+
+#endif
diff --git a/UefiCpuPkg/Include/Register/Amd/Msr.h b/UefiCpuPkg/Include/Register/Amd/Msr.h
new file mode 100644
index 000000000000..bde830feb0c5
--- /dev/null
+++ b/UefiCpuPkg/Include/Register/Amd/Msr.h
@@ -0,0 +1,29 @@
+/** @file
+ MSR Definitions.
+
+ Provides defines for Machine Specific Registers(MSR) indexes. Data structures
+ are provided for MSRs that contain one or more bit fields. If the MSR value
+ returned is a single 32-bit or 64-bit value, then a data structure is not
+ provided for that MSR.
+
+ 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.
+
+ @par Specification Reference:
+ AMD64 Architecture Programming Manaul volume 2, March 2017, Sections 15.34
+
+**/
+
+#ifndef __AMD_MSR_H__
+#define __AMD_MSR_H__
+
+#include <Register/ArchitecturalMsr.h>
+#include <Register/Amd/Fam17Msr.h>
+
+#endif
--
2.7.4
^ permalink raw reply related [flat|nested] 42+ messages in thread
* Re: [RFC v4 01/13] UefiCpuPkg: Define AMD Memory Encryption specific CPUID and MSR
2017-05-10 22:09 ` [RFC v4 01/13] UefiCpuPkg: Define AMD Memory Encryption specific CPUID and MSR Brijesh Singh
@ 2017-05-11 0:30 ` Fan, Jeff
0 siblings, 0 replies; 42+ messages in thread
From: Fan, Jeff @ 2017-05-11 0:30 UTC (permalink / raw)
To: Brijesh Singh, edk2-devel@lists.01.org
Cc: Thomas.Lendacky@amd.com, leo.duran@amd.com, Justen, Jordan L,
Laszlo Ersek, Gao, Liming
Reviewed-by: Jeff Fan <jeff.fan@intel.com>
-----Original Message-----
From: Brijesh Singh [mailto:brijesh.singh@amd.com]
Sent: Thursday, May 11, 2017 6:09 AM
To: edk2-devel@lists.01.org
Cc: Thomas.Lendacky@amd.com; leo.duran@amd.com; Brijesh Singh; Justen, Jordan L; Laszlo Ersek; Fan, Jeff; Gao, Liming
Subject: [RFC v4 01/13] UefiCpuPkg: Define AMD Memory Encryption specific CPUID and MSR
The patch defines AMD's Memory Encryption Information CPUID leaf and SEV status MSR. The complete description for CPUID leaf is available in APM volume 2, Section 15.34.
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Cc: Jeff Fan <jeff.fan@intel.com>
Cc: Liming Gao <liming.gao@intel.com>
Cc: Leo Duran <leo.duran@amd.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
---
UefiCpuPkg/Include/Register/Amd/Cpuid.h | 162 ++++++++++++++++++++
UefiCpuPkg/Include/Register/Amd/Fam17Msr.h | 62 ++++++++
UefiCpuPkg/Include/Register/Amd/Msr.h | 29 ++++
3 files changed, 253 insertions(+)
diff --git a/UefiCpuPkg/Include/Register/Amd/Cpuid.h b/UefiCpuPkg/Include/Register/Amd/Cpuid.h
new file mode 100644
index 000000000000..5cd42667dc46
--- /dev/null
+++ b/UefiCpuPkg/Include/Register/Amd/Cpuid.h
@@ -0,0 +1,162 @@
+/** @file
+ CPUID leaf definitions.
+
+ Provides defines for CPUID leaf indexes. Data structures are
+ provided for registers returned by a CPUID leaf that contain one or more bit fields.
+ If a register returned is a single 32-bit value, then a data
+ structure is not provided for that register.
+
+ 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.
+
+ @par Specification Reference:
+ AMD64 Architecture Programming Manaul volume 2, March 2017, Sections
+ 15.34
+
+**/
+
+#ifndef __AMD_CPUID_H__
+#define __AMD_CPUID_H__
+
+/**
+
+ Memory Encryption Information
+
+ @param EAX CPUID_MEMORY_ENCRYPTION_INFO (0x8000001F)
+
+ @retval EAX Returns the memory encryption feature support status.
+ @retval EBX If memory encryption feature is present then return
+ the page table bit number used to enable memory encryption support
+ and reducing of physical address space in bits.
+ @retval ECX Returns number of encrypted guest supported simultaneosuly.
+ @retval EDX Returns minimum SEV enabled and SEV disbled ASID..
+
+ <b>Example usage</b>
+ @code
+ UINT32 Eax;
+ UINT32 Ebx;
+ UINT32 Ecx;
+ UINT32 Edx;
+
+ AsmCpuid (CPUID_MEMORY_ENCRYPTION_INFO, &Eax, &Ebx, &Ecx, &Edx);
+ @endcode
+**/
+
+#define CPUID_MEMORY_ENCRYPTION_INFO 0x8000001F
+
+/**
+ CPUID Memory Encryption support information EAX for CPUID leaf
+ #CPUID_MEMORY_ENCRYPTION_INFO.
+**/
+typedef union {
+ ///
+ /// Individual bit fields
+ ///
+ struct {
+ ///
+ /// [Bit 0] Secure Memory Encryption (Sme) Support
+ ///
+ UINT32 SmeBit:1;
+
+ ///
+ /// [Bit 1] Secure Encrypted Virtualization (Sev) Support
+ ///
+ UINT32 SevBit:1;
+
+ ///
+ /// [Bit 2] Page flush MSR support
+ ///
+ UINT32 PageFlushMsrBit:1;
+
+ ///
+ /// [Bit 3] Encrypted state support
+ ///
+ UINT32 SevEsBit:1;
+
+ ///
+ /// [Bit 4:31] Reserved
+ ///
+ UINT32 ReservedBits:28;
+ } Bits;
+ ///
+ /// All bit fields as a 32-bit value
+ ///
+ UINT32 Uint32;
+} CPUID_MEMORY_ENCRYPTION_INFO_EAX;
+
+/**
+ CPUID Memory Encryption support information EBX for CPUID leaf
+ #CPUID_MEMORY_ENCRYPTION_INFO.
+**/
+typedef union {
+ ///
+ /// Individual bit fields
+ ///
+ struct {
+ ///
+ /// [Bit 0:5] Page table bit number used to enable memory encryption
+ ///
+ UINT32 PtePosBits:6;
+
+ ///
+ /// [Bit 6:11] Reduction of system physical address space bits when memory encryption is enabled
+ ///
+ UINT32 ReducedPhysBits:5;
+
+ ///
+ /// [Bit 12:31] Reserved
+ ///
+ UINT32 ReservedBits:21;
+ } Bits;
+ ///
+ /// All bit fields as a 32-bit value
+ ///
+ UINT32 Uint32;
+} CPUID_MEMORY_ENCRYPTION_INFO_EBX;
+
+/**
+ CPUID Memory Encryption support information ECX for CPUID leaf
+ #CPUID_MEMORY_ENCRYPTION_INFO.
+**/
+typedef union {
+ ///
+ /// Individual bit fields
+ ///
+ struct {
+ ///
+ /// [Bit 0:31] Number of encrypted guest supported simultaneously
+ ///
+ UINT32 NumGuests;
+ } Bits;
+ ///
+ /// All bit fields as a 32-bit value
+ ///
+ UINT32 Uint32;
+} CPUID_MEMORY_ENCRYPTION_INFO_ECX;
+
+/**
+ CPUID Memory Encryption support information EDX for CPUID leaf
+ #CPUID_MEMORY_ENCRYPTION_INFO.
+**/
+typedef union {
+ ///
+ /// Individual bit fields
+ ///
+ struct {
+ ///
+ /// [Bit 0:31] Minimum SEV enabled, SEV-ES disabled ASID
+ ///
+ UINT32 MinAsid;
+ } Bits;
+ ///
+ /// All bit fields as a 32-bit value
+ ///
+ UINT32 Uint32;
+} CPUID_MEMORY_ENCRYPTION_INFO_EDX;
+
+#endif
diff --git a/UefiCpuPkg/Include/Register/Amd/Fam17Msr.h b/UefiCpuPkg/Include/Register/Amd/Fam17Msr.h
new file mode 100644
index 000000000000..2c5d9738fae8
--- /dev/null
+++ b/UefiCpuPkg/Include/Register/Amd/Fam17Msr.h
@@ -0,0 +1,62 @@
+/** @file
+ MSR Definitions.
+
+ Provides defines for Machine Specific Registers(MSR) indexes. Data
+ structures are provided for MSRs that contain one or more bit fields.
+ If the MSR value returned is a single 32-bit or 64-bit value, then a
+ data structure is not provided for that MSR.
+
+ 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.
+
+ @par Specification Reference:
+ AMD64 Architecture Programming Manaul volume 2, March 2017, Sections
+ 15.34
+
+**/
+
+#ifndef __FAM17_MSR_H
+#define __FAM17_MSR_H
+
+/**
+ Secure Encrypted Virtualization (SEV) status register
+
+**/
+#define MSR_SEV_STATUS 0xc0010131
+
+/**
+ MSR information returned for #MSR_SEV_STATUS **/ typedef union {
+ ///
+ /// Individual bit fields
+ ///
+ struct {
+ ///
+ /// [Bit 0] Secure Encrypted Virtualization (Sev) is enabled
+ ///
+ UINT32 SevBit:1;
+
+ ///
+ /// [Bit 1] Secure Encrypted Virtualization Encrypted State (SevEs) is enabled
+ ///
+ UINT32 SevEsBit:1;
+
+ UINT32 Reserved:30;
+ } Bits;
+ ///
+ /// All bit fields as a 32-bit value
+ ///
+ UINT32 Uint32;
+ ///
+ /// All bit fields as a 64-bit value
+ ///
+ UINT64 Uint64;
+} MSR_SEV_STATUS_REGISTER;
+
+#endif
diff --git a/UefiCpuPkg/Include/Register/Amd/Msr.h b/UefiCpuPkg/Include/Register/Amd/Msr.h
new file mode 100644
index 000000000000..bde830feb0c5
--- /dev/null
+++ b/UefiCpuPkg/Include/Register/Amd/Msr.h
@@ -0,0 +1,29 @@
+/** @file
+ MSR Definitions.
+
+ Provides defines for Machine Specific Registers(MSR) indexes. Data
+ structures are provided for MSRs that contain one or more bit fields.
+ If the MSR value returned is a single 32-bit or 64-bit value, then a
+ data structure is not provided for that MSR.
+
+ 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.
+
+ @par Specification Reference:
+ AMD64 Architecture Programming Manaul volume 2, March 2017, Sections
+ 15.34
+
+**/
+
+#ifndef __AMD_MSR_H__
+#define __AMD_MSR_H__
+
+#include <Register/ArchitecturalMsr.h>
+#include <Register/Amd/Fam17Msr.h>
+
+#endif
--
2.7.4
^ permalink raw reply related [flat|nested] 42+ messages in thread
* [RFC v4 02/13] OvmfPkg/ResetVector: Set C-bit when building initial page table
2017-05-10 22:09 [RFC v4 00/13] x86: Secure Encrypted Virtualization (AMD) Brijesh Singh
2017-05-10 22:09 ` [RFC v4 01/13] UefiCpuPkg: Define AMD Memory Encryption specific CPUID and MSR Brijesh Singh
@ 2017-05-10 22:09 ` Brijesh Singh
2017-05-11 11:40 ` Laszlo Ersek
2017-05-10 22:09 ` [RFC v4 03/13] OvmfPkg: Update dsc to use IoLib from BaseIoLibIntrinsicSev.inf Brijesh Singh
` (10 subsequent siblings)
12 siblings, 1 reply; 42+ messages in thread
From: Brijesh Singh @ 2017-05-10 22:09 UTC (permalink / raw)
To: edk2-devel
Cc: Thomas.Lendacky, leo.duran, Brijesh Singh, Jordan Justen,
Laszlo Ersek
SEV guest VMs have the concept of private and shared memory. Private
memory is encrypted with the guest-specific key, while shared memory
may be encrypted with hypervisor key. Certain types of memory (namely
instruction pages and guest page tables) are always treated as private
memory by the hardware. The C-bit in PTE indicate whether the page is
private or shared. The C-bit position for the PTE can be obtained from
CPUID Fn8000_001F[EBX].
When SEV is active, the BIOS is encrypted by the Qemu launch sequence,
we must set the C-bit when building the page table.
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Cc: Tom Lendacky <Thomas.Lendacky@amd.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
---
OvmfPkg/ResetVector/Ia32/PageTables64.asm | 70 +++++++++++++++++++-
1 file changed, 69 insertions(+), 1 deletion(-)
diff --git a/OvmfPkg/ResetVector/Ia32/PageTables64.asm b/OvmfPkg/ResetVector/Ia32/PageTables64.asm
index 6201cad1f5dc..3d4b04844cdf 100644
--- a/OvmfPkg/ResetVector/Ia32/PageTables64.asm
+++ b/OvmfPkg/ResetVector/Ia32/PageTables64.asm
@@ -37,9 +37,60 @@ BITS 32
PAGE_READ_WRITE + \
PAGE_PRESENT)
+; Check if Secure Encrypted Virtualization (SEV) feature is enabled
+;
+; If SEV is enabled then EAX will be at least 32
+; If SEV is disabled then EAX will be zero.
+;
+CheckSevFeature:
+ ; CPUID will clobber EBX, ECX, EDX, save these registers
+ push ebx
+ push ecx
+ push edx
+
+ ; Check if we have a valid (0x8000_001F) CPUID leaf
+ mov eax, 0x80000000
+ cpuid
+
+ ; This check should fail on Intel or Non SEV AMD CPUs and in future if
+ ; Intel CPUs supports this CPUID leaf then we are guranteed to have exact
+ ; same bit definition.
+ cmp eax, 0x8000001f
+ jl NoSev
+
+ ; Check for memory encryption feature:
+ ; CPUID Fn8000_001F[EAX] - Bit 1
+ ;
+ mov eax, 0x8000001f
+ cpuid
+ bt eax, 1
+ jnc NoSev
+
+ ; Check if memory encryption is enabled
+ ; MSR_0xC0010131 - Bit 0 (SEV enabled)
+ mov ecx, 0xc0010131
+ rdmsr
+ bt eax, 0
+ jnc NoSev
+
+ ; Get pte bit position to enable memory encryption
+ ; CPUID Fn8000_001F[EBX] - Bits 5:0
+ ;
+ mov eax, ebx
+ and eax, 0x3f
+ jmp SevExit
+
+NoSev:
+ xor eax, eax
+
+SevExit:
+ pop edx
+ pop ecx
+ pop ebx
+ OneTimeCallRet CheckSevFeature
;
-; Modified: EAX, ECX
+; Modified: EAX, ECX, EDX
;
SetCr3ForPageTables64:
@@ -60,18 +111,34 @@ clearPageTablesMemoryLoop:
mov dword[ecx * 4 + PT_ADDR (0) - 4], eax
loop clearPageTablesMemoryLoop
+ OneTimeCall CheckSevFeature
+ xor edx, edx
+ test eax, eax
+ jz SevNotActive
+
+ ; If SEV is enabled, Memory encryption bit is always above 31
+ sub eax, 32
+ bts edx, eax
+
+SevNotActive:
+
;
; Top level Page Directory Pointers (1 * 512GB entry)
;
mov dword[PT_ADDR (0)], PT_ADDR (0x1000) + PAGE_PDP_ATTR
+ mov dword[PT_ADDR (4)], edx
;
; Next level Page Directory Pointers (4 * 1GB entries => 4GB)
;
mov dword[PT_ADDR (0x1000)], PT_ADDR (0x2000) + PAGE_PDP_ATTR
+ mov dword[PT_ADDR (0x1004)], edx
mov dword[PT_ADDR (0x1008)], PT_ADDR (0x3000) + PAGE_PDP_ATTR
+ mov dword[PT_ADDR (0x100C)], edx
mov dword[PT_ADDR (0x1010)], PT_ADDR (0x4000) + PAGE_PDP_ATTR
+ mov dword[PT_ADDR (0x1014)], edx
mov dword[PT_ADDR (0x1018)], PT_ADDR (0x5000) + PAGE_PDP_ATTR
+ mov dword[PT_ADDR (0x101C)], edx
;
; Page Table Entries (2048 * 2MB entries => 4GB)
@@ -83,6 +150,7 @@ pageTableEntriesLoop:
shl eax, 21
add eax, PAGE_2M_PDE_ATTR
mov [ecx * 8 + PT_ADDR (0x2000 - 8)], eax
+ mov [(ecx * 8 + PT_ADDR (0x2000 - 8)) + 4], edx
loop pageTableEntriesLoop
;
--
2.7.4
^ permalink raw reply related [flat|nested] 42+ messages in thread
* Re: [RFC v4 02/13] OvmfPkg/ResetVector: Set C-bit when building initial page table
2017-05-10 22:09 ` [RFC v4 02/13] OvmfPkg/ResetVector: Set C-bit when building initial page table Brijesh Singh
@ 2017-05-11 11:40 ` Laszlo Ersek
0 siblings, 0 replies; 42+ messages in thread
From: Laszlo Ersek @ 2017-05-11 11:40 UTC (permalink / raw)
To: Brijesh Singh, edk2-devel; +Cc: Thomas.Lendacky, leo.duran, Jordan Justen
On 05/11/17 00:09, Brijesh Singh wrote:
> SEV guest VMs have the concept of private and shared memory. Private
> memory is encrypted with the guest-specific key, while shared memory
> may be encrypted with hypervisor key. Certain types of memory (namely
> instruction pages and guest page tables) are always treated as private
> memory by the hardware. The C-bit in PTE indicate whether the page is
> private or shared. The C-bit position for the PTE can be obtained from
> CPUID Fn8000_001F[EBX].
>
> When SEV is active, the BIOS is encrypted by the Qemu launch sequence,
> we must set the C-bit when building the page table.
>
>
> Cc: Jordan Justen <jordan.l.justen@intel.com>
> Cc: Laszlo Ersek <lersek@redhat.com>
> Cc: Tom Lendacky <Thomas.Lendacky@amd.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
> ---
> OvmfPkg/ResetVector/Ia32/PageTables64.asm | 70 +++++++++++++++++++-
> 1 file changed, 69 insertions(+), 1 deletion(-)
>
> diff --git a/OvmfPkg/ResetVector/Ia32/PageTables64.asm b/OvmfPkg/ResetVector/Ia32/PageTables64.asm
> index 6201cad1f5dc..3d4b04844cdf 100644
> --- a/OvmfPkg/ResetVector/Ia32/PageTables64.asm
> +++ b/OvmfPkg/ResetVector/Ia32/PageTables64.asm
> @@ -37,9 +37,60 @@ BITS 32
> PAGE_READ_WRITE + \
> PAGE_PRESENT)
>
> +; Check if Secure Encrypted Virtualization (SEV) feature is enabled
> +;
> +; If SEV is enabled then EAX will be at least 32
> +; If SEV is disabled then EAX will be zero.
> +;
> +CheckSevFeature:
> + ; CPUID will clobber EBX, ECX, EDX, save these registers
> + push ebx
> + push ecx
> + push edx
> +
> + ; Check if we have a valid (0x8000_001F) CPUID leaf
> + mov eax, 0x80000000
> + cpuid
> +
> + ; This check should fail on Intel or Non SEV AMD CPUs and in future if
> + ; Intel CPUs supports this CPUID leaf then we are guranteed to have exact
> + ; same bit definition.
> + cmp eax, 0x8000001f
> + jl NoSev
> +
> + ; Check for memory encryption feature:
> + ; CPUID Fn8000_001F[EAX] - Bit 1
> + ;
> + mov eax, 0x8000001f
> + cpuid
> + bt eax, 1
> + jnc NoSev
> +
> + ; Check if memory encryption is enabled
> + ; MSR_0xC0010131 - Bit 0 (SEV enabled)
> + mov ecx, 0xc0010131
> + rdmsr
> + bt eax, 0
> + jnc NoSev
> +
> + ; Get pte bit position to enable memory encryption
> + ; CPUID Fn8000_001F[EBX] - Bits 5:0
> + ;
> + mov eax, ebx
> + and eax, 0x3f
> + jmp SevExit
> +
> +NoSev:
> + xor eax, eax
> +
> +SevExit:
> + pop edx
> + pop ecx
> + pop ebx
> + OneTimeCallRet CheckSevFeature
>
> ;
> -; Modified: EAX, ECX
> +; Modified: EAX, ECX, EDX
> ;
> SetCr3ForPageTables64:
>
> @@ -60,18 +111,34 @@ clearPageTablesMemoryLoop:
> mov dword[ecx * 4 + PT_ADDR (0) - 4], eax
> loop clearPageTablesMemoryLoop
>
> + OneTimeCall CheckSevFeature
> + xor edx, edx
> + test eax, eax
> + jz SevNotActive
> +
> + ; If SEV is enabled, Memory encryption bit is always above 31
> + sub eax, 32
> + bts edx, eax
> +
> +SevNotActive:
> +
> ;
> ; Top level Page Directory Pointers (1 * 512GB entry)
> ;
> mov dword[PT_ADDR (0)], PT_ADDR (0x1000) + PAGE_PDP_ATTR
> + mov dword[PT_ADDR (4)], edx
>
> ;
> ; Next level Page Directory Pointers (4 * 1GB entries => 4GB)
> ;
> mov dword[PT_ADDR (0x1000)], PT_ADDR (0x2000) + PAGE_PDP_ATTR
> + mov dword[PT_ADDR (0x1004)], edx
> mov dword[PT_ADDR (0x1008)], PT_ADDR (0x3000) + PAGE_PDP_ATTR
> + mov dword[PT_ADDR (0x100C)], edx
> mov dword[PT_ADDR (0x1010)], PT_ADDR (0x4000) + PAGE_PDP_ATTR
> + mov dword[PT_ADDR (0x1014)], edx
> mov dword[PT_ADDR (0x1018)], PT_ADDR (0x5000) + PAGE_PDP_ATTR
> + mov dword[PT_ADDR (0x101C)], edx
>
> ;
> ; Page Table Entries (2048 * 2MB entries => 4GB)
> @@ -83,6 +150,7 @@ pageTableEntriesLoop:
> shl eax, 21
> add eax, PAGE_2M_PDE_ATTR
> mov [ecx * 8 + PT_ADDR (0x2000 - 8)], eax
> + mov [(ecx * 8 + PT_ADDR (0x2000 - 8)) + 4], edx
> loop pageTableEntriesLoop
>
> ;
>
Reviewed-by: Laszlo Ersek <lersek@redhat.com>
^ permalink raw reply [flat|nested] 42+ messages in thread
* [RFC v4 03/13] OvmfPkg: Update dsc to use IoLib from BaseIoLibIntrinsicSev.inf
2017-05-10 22:09 [RFC v4 00/13] x86: Secure Encrypted Virtualization (AMD) Brijesh Singh
2017-05-10 22:09 ` [RFC v4 01/13] UefiCpuPkg: Define AMD Memory Encryption specific CPUID and MSR Brijesh Singh
2017-05-10 22:09 ` [RFC v4 02/13] OvmfPkg/ResetVector: Set C-bit when building initial page table Brijesh Singh
@ 2017-05-10 22:09 ` Brijesh Singh
2017-05-11 11:46 ` Laszlo Ersek
2017-05-10 22:09 ` [RFC v4 04/13] OvmfPkg/BaseMemcryptSevLib: Add SEV helper library Brijesh Singh
` (9 subsequent siblings)
12 siblings, 1 reply; 42+ messages in thread
From: Brijesh Singh @ 2017-05-10 22:09 UTC (permalink / raw)
To: edk2-devel
Cc: Thomas.Lendacky, leo.duran, Brijesh Singh, Jordan Justen,
Laszlo Ersek
When SEV is enabled then we must unroll the rep String I/O instructions.
The patch updates dsc file to use SEV version of IoLib inf. The main
difference between BaseIoLibIntrinsic.inf and BaseIoLibIntrinsicSev.inf
is, SEV version checks if its running under SEV enabled guest, If so
then it unroll the String I/O (REP INS/OUTS) otherwise fallbacks to
rep ins/outs.
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
---
OvmfPkg/OvmfPkgIa32.dsc | 2 +-
OvmfPkg/OvmfPkgIa32X64.dsc | 2 +-
OvmfPkg/OvmfPkgX64.dsc | 2 +-
3 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc
index e0779ddaa426..6494ac5480b3 100644
--- a/OvmfPkg/OvmfPkgIa32.dsc
+++ b/OvmfPkg/OvmfPkgIa32.dsc
@@ -120,7 +120,7 @@ [LibraryClasses]
PciExpressLib|MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf
PciLib|MdePkg/Library/BasePciLibCf8/BasePciLibCf8.inf
PciSegmentLib|MdePkg/Library/BasePciSegmentLibPci/BasePciSegmentLibPci.inf
- IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
+ IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf
OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf
SerialPortLib|PcAtChipsetPkg/Library/SerialIoLib/SerialIoLib.inf
MtrrLib|UefiCpuPkg/Library/MtrrLib/MtrrLib.inf
diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
index bbe26e2cf452..20eb409a8d01 100644
--- a/OvmfPkg/OvmfPkgIa32X64.dsc
+++ b/OvmfPkg/OvmfPkgIa32X64.dsc
@@ -125,7 +125,7 @@ [LibraryClasses]
PciExpressLib|MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf
PciLib|MdePkg/Library/BasePciLibCf8/BasePciLibCf8.inf
PciSegmentLib|MdePkg/Library/BasePciSegmentLibPci/BasePciSegmentLibPci.inf
- IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
+ IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf
OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf
SerialPortLib|PcAtChipsetPkg/Library/SerialIoLib/SerialIoLib.inf
MtrrLib|UefiCpuPkg/Library/MtrrLib/MtrrLib.inf
diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
index ff795815f65f..2e5eaf631e9f 100644
--- a/OvmfPkg/OvmfPkgX64.dsc
+++ b/OvmfPkg/OvmfPkgX64.dsc
@@ -125,7 +125,7 @@ [LibraryClasses]
PciExpressLib|MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf
PciLib|MdePkg/Library/BasePciLibCf8/BasePciLibCf8.inf
PciSegmentLib|MdePkg/Library/BasePciSegmentLibPci/BasePciSegmentLibPci.inf
- IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
+ IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf
OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf
SerialPortLib|PcAtChipsetPkg/Library/SerialIoLib/SerialIoLib.inf
MtrrLib|UefiCpuPkg/Library/MtrrLib/MtrrLib.inf
--
2.7.4
^ permalink raw reply related [flat|nested] 42+ messages in thread
* Re: [RFC v4 03/13] OvmfPkg: Update dsc to use IoLib from BaseIoLibIntrinsicSev.inf
2017-05-10 22:09 ` [RFC v4 03/13] OvmfPkg: Update dsc to use IoLib from BaseIoLibIntrinsicSev.inf Brijesh Singh
@ 2017-05-11 11:46 ` Laszlo Ersek
0 siblings, 0 replies; 42+ messages in thread
From: Laszlo Ersek @ 2017-05-11 11:46 UTC (permalink / raw)
To: Brijesh Singh, edk2-devel; +Cc: Thomas.Lendacky, leo.duran, Jordan Justen
On 05/11/17 00:09, Brijesh Singh wrote:
> When SEV is enabled then we must unroll the rep String I/O instructions.
>
> The patch updates dsc file to use SEV version of IoLib inf. The main
> difference between BaseIoLibIntrinsic.inf and BaseIoLibIntrinsicSev.inf
> is, SEV version checks if its running under SEV enabled guest, If so
> then it unroll the String I/O (REP INS/OUTS) otherwise fallbacks to
> rep ins/outs.
>
>
> Cc: Jordan Justen <jordan.l.justen@intel.com>
> Cc: Laszlo Ersek <lersek@redhat.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
> ---
> OvmfPkg/OvmfPkgIa32.dsc | 2 +-
> OvmfPkg/OvmfPkgIa32X64.dsc | 2 +-
> OvmfPkg/OvmfPkgX64.dsc | 2 +-
> 3 files changed, 3 insertions(+), 3 deletions(-)
>
> diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc
> index e0779ddaa426..6494ac5480b3 100644
> --- a/OvmfPkg/OvmfPkgIa32.dsc
> +++ b/OvmfPkg/OvmfPkgIa32.dsc
> @@ -120,7 +120,7 @@ [LibraryClasses]
> PciExpressLib|MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf
> PciLib|MdePkg/Library/BasePciLibCf8/BasePciLibCf8.inf
> PciSegmentLib|MdePkg/Library/BasePciSegmentLibPci/BasePciSegmentLibPci.inf
> - IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
> + IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf
> OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf
> SerialPortLib|PcAtChipsetPkg/Library/SerialIoLib/SerialIoLib.inf
> MtrrLib|UefiCpuPkg/Library/MtrrLib/MtrrLib.inf
> diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
> index bbe26e2cf452..20eb409a8d01 100644
> --- a/OvmfPkg/OvmfPkgIa32X64.dsc
> +++ b/OvmfPkg/OvmfPkgIa32X64.dsc
> @@ -125,7 +125,7 @@ [LibraryClasses]
> PciExpressLib|MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf
> PciLib|MdePkg/Library/BasePciLibCf8/BasePciLibCf8.inf
> PciSegmentLib|MdePkg/Library/BasePciSegmentLibPci/BasePciSegmentLibPci.inf
> - IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
> + IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf
> OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf
> SerialPortLib|PcAtChipsetPkg/Library/SerialIoLib/SerialIoLib.inf
> MtrrLib|UefiCpuPkg/Library/MtrrLib/MtrrLib.inf
> diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
> index ff795815f65f..2e5eaf631e9f 100644
> --- a/OvmfPkg/OvmfPkgX64.dsc
> +++ b/OvmfPkg/OvmfPkgX64.dsc
> @@ -125,7 +125,7 @@ [LibraryClasses]
> PciExpressLib|MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf
> PciLib|MdePkg/Library/BasePciLibCf8/BasePciLibCf8.inf
> PciSegmentLib|MdePkg/Library/BasePciSegmentLibPci/BasePciSegmentLibPci.inf
> - IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
> + IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf
> OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf
> SerialPortLib|PcAtChipsetPkg/Library/SerialIoLib/SerialIoLib.inf
> MtrrLib|UefiCpuPkg/Library/MtrrLib/MtrrLib.inf
>
Reviewed-by: Laszlo Ersek <lersek@redhat.com>
^ permalink raw reply [flat|nested] 42+ messages in thread
* [RFC v4 04/13] OvmfPkg/BaseMemcryptSevLib: Add SEV helper library
2017-05-10 22:09 [RFC v4 00/13] x86: Secure Encrypted Virtualization (AMD) Brijesh Singh
` (2 preceding siblings ...)
2017-05-10 22:09 ` [RFC v4 03/13] OvmfPkg: Update dsc to use IoLib from BaseIoLibIntrinsicSev.inf Brijesh Singh
@ 2017-05-10 22:09 ` Brijesh Singh
2017-05-11 14:04 ` Laszlo Ersek
2017-05-10 22:09 ` [RFC v4 05/13] OvmfPkg/PlatformPei: Set memory encryption PCD when SEV is enabled Brijesh Singh
` (8 subsequent siblings)
12 siblings, 1 reply; 42+ messages in thread
From: Brijesh Singh @ 2017-05-10 22:09 UTC (permalink / raw)
To: edk2-devel
Cc: Thomas.Lendacky, leo.duran, Brijesh Singh, Jordan Justen,
Laszlo Ersek
Add Secure Encrypted Virtualization (SEV) helper library.
The library provides the routines to:
- set or clear memory encryption bit for a given memory region.
- query whether SEV is enabled.
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
---
OvmfPkg/OvmfPkgIa32.dsc | 1 +
OvmfPkg/OvmfPkgIa32X64.dsc | 1 +
OvmfPkg/OvmfPkgX64.dsc | 1 +
OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf | 50 +++
OvmfPkg/Include/Library/MemEncryptSevLib.h | 81 ++++
OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.h | 34 ++
OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h | 184 +++++++++
OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c | 126 ++++++
OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c | 43 ++
OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c | 127 ++++++
OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c | 422 ++++++++++++++++++++
11 files changed, 1070 insertions(+)
diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc
index 6494ac5480b3..265f2d2b6d2f 100644
--- a/OvmfPkg/OvmfPkgIa32.dsc
+++ b/OvmfPkg/OvmfPkgIa32.dsc
@@ -143,6 +143,7 @@ [LibraryClasses]
QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf
LoadLinuxLib|OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.inf
+ MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
!if $(SMM_REQUIRE) == FALSE
LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf
!endif
diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
index 20eb409a8d01..3b50a2dd2d2f 100644
--- a/OvmfPkg/OvmfPkgIa32X64.dsc
+++ b/OvmfPkg/OvmfPkgIa32X64.dsc
@@ -148,6 +148,7 @@ [LibraryClasses]
QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf
LoadLinuxLib|OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.inf
+ MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
!if $(SMM_REQUIRE) == FALSE
LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf
!endif
diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
index 2e5eaf631e9f..82c73331aa9f 100644
--- a/OvmfPkg/OvmfPkgX64.dsc
+++ b/OvmfPkg/OvmfPkgX64.dsc
@@ -148,6 +148,7 @@ [LibraryClasses]
QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf
LoadLinuxLib|OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.inf
+ MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
!if $(SMM_REQUIRE) == FALSE
LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf
!endif
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf b/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
new file mode 100644
index 000000000000..949c430af61b
--- /dev/null
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
@@ -0,0 +1,50 @@
+## @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.
+#
+#
+##
+
+[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
+ OvmfPkg/OvmfPkg.dec
+ UefiCpuPkg/UefiCpuPkg.dec
+
+[Sources.X64]
+ X64/MemEncryptSevLib.c
+ X64/VirtualMemory.c
+ MemEncryptSevLibInternal.c
+
+[Sources.IA32]
+ Ia32/MemEncryptSevLib.c
+ MemEncryptSevLibInternal.c
+
+[LibraryClasses]
+ BaseLib
+ CpuLib
+ CacheMaintenanceLib
+ DebugLib
+ MemoryAllocationLib
diff --git a/OvmfPkg/Include/Library/MemEncryptSevLib.h b/OvmfPkg/Include/Library/MemEncryptSevLib.h
new file mode 100644
index 000000000000..b6753762423e
--- /dev/null
+++ b/OvmfPkg/Include/Library/MemEncryptSevLib.h
@@ -0,0 +1,81 @@
+/** @file
+
+ Define Secure Encrypted Virtualization (SEV) base 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.
+
+**/
+
+#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 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.
+ @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] 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
+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/MemEncryptSevLibInternal.h b/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.h
new file mode 100644
index 000000000000..17f67b47dbee
--- /dev/null
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.h
@@ -0,0 +1,34 @@
+/** @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.
+
+**/
+
+#ifndef _MEM_ENCRYPT_SEV_LIB_INTERNAL_H_
+#define _MEM_ENCRYPT_SEV_LIB_INTERNAL_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
+InternalMemEncryptSevIsEnabled (
+ VOID
+ );
+
+#endif
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h
new file mode 100644
index 000000000000..ab5a6ddc3e85
--- /dev/null
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h
@@ -0,0 +1,184 @@
+/** @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.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 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)
+ 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 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)
+ 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 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
+ } 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 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)
+ 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 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
+ } 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 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)
+ 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 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
+ } Bits;
+ UINT64 Uint64;
+} PAGE_TABLE_1G_ENTRY;
+
+#pragma pack()
+
+#define IA32_PG_P BIT0
+#define IA32_PG_RW BIT1
+
+#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
+
+/**
+ 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_INVALID_PARAMETER Number of pages is zero.
+ @retval RETURN_UNSUPPORTED Setting the memory encyrption attribute is not supported
+**/
+EFI_STATUS
+EFIAPI
+SetMemoryDecrypted (
+ 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] 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
+**/
+EFI_STATUS
+EFIAPI
+SetMemoryEncrypted (
+ 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
new file mode 100644
index 000000000000..4b7f421475ac
--- /dev/null
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c
@@ -0,0 +1,126 @@
+/** @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 "Uefi.h"
+#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 "MemEncryptSevLibInternal.h"
+
+/**
+
+ Returns a boolean to indicate whether SEV is enabled
+
+ @retval TRUE SEV is enabled
+ @retval FALSE SEV is not enabled
+ **/
+BOOLEAN
+EFIAPI
+InternalMemEncryptSevIsEnabled (
+ VOID
+ )
+{
+ UINT32 RegEax;
+ MSR_SEV_STATUS_REGISTER Msr;
+ CPUID_MEMORY_ENCRYPTION_INFO_EAX Eax;
+
+ //
+ // Check if memory encryption leaf exist
+ //
+ AsmCpuid (CPUID_EXTENDED_FUNCTION, &RegEax, NULL, NULL, NULL);
+ if (RegEax >= CPUID_MEMORY_ENCRYPTION_INFO) {
+ //
+ // 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 is Enabled)
+ //
+ Msr.Uint32 = AsmReadMsr32 (MSR_SEV_STATUS);
+ if (Msr.Bits.SevBit) {
+ return TRUE;
+ }
+ }
+ }
+
+ return FALSE;
+}
+
+/**
+ 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.
+ @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] 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
+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
new file mode 100644
index 000000000000..43ecba7a28bb
--- /dev/null
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c
@@ -0,0 +1,43 @@
+/** @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 "MemEncryptSevLibInternal.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
+ **/
+BOOLEAN
+EFIAPI
+MemEncryptSevIsEnabled (
+ VOID
+ )
+{
+ if (mSevStatusChecked) {
+ return mSevStatus;
+ }
+
+ mSevStatus = InternalMemEncryptSevIsEnabled();
+ mSevStatusChecked = TRUE;
+
+ return mSevStatus;
+}
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c
new file mode 100644
index 000000000000..92f701497ffb
--- /dev/null
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c
@@ -0,0 +1,127 @@
+/** @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 "Uefi.h"
+#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"
+#include "MemEncryptSevLibInternal.h"
+
+/**
+
+ Returns a boolean to indicate whether SEV is enabled
+
+ @retval TRUE SEV is enabled
+ @retval FALSE SEV is not enabled
+ **/
+BOOLEAN
+EFIAPI
+InternalMemEncryptSevIsEnabled (
+ VOID
+ )
+{
+ UINT32 RegEax;
+ MSR_SEV_STATUS_REGISTER Msr;
+ CPUID_MEMORY_ENCRYPTION_INFO_EAX Eax;
+
+ //
+ // Check if memory encryption leaf exist
+ //
+ AsmCpuid (CPUID_EXTENDED_FUNCTION, &RegEax, NULL, NULL, NULL);
+ if (RegEax >= CPUID_MEMORY_ENCRYPTION_INFO) {
+ //
+ // 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;
+}
+
+/**
+
+ 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] 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 SetMemoryDecrypted (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] 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
+MemEncryptSevSetPageEncMask (
+ IN PHYSICAL_ADDRESS Cr3BaseAddress,
+ IN PHYSICAL_ADDRESS BaseAddress,
+ IN UINTN NumPages,
+ IN BOOLEAN Flush
+ )
+{
+ return SetMemoryEncrypted (Cr3BaseAddress, BaseAddress, EFI_PAGES_TO_SIZE(NumPages), Flush);
+}
diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
new file mode 100644
index 000000000000..51425830baa5
--- /dev/null
+++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
@@ -0,0 +1,422 @@
+/** @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 "VirtualMemory.h"
+
+STATIC BOOLEAN mAddressEncMaskChecked = FALSE;
+STATIC UINT64 mAddressEncMask;
+
+typedef enum {
+ SetCBit,
+ ClearCBit
+} MAP_RANGE_MODE;
+
+/**
+ Get the memory encryption mask
+
+ @param[out] EncryptionMask contains the pte mask.
+
+**/
+STATIC
+UINT64
+GetMemEncryptionAddressMask (
+ VOID
+ )
+{
+ UINT64 EncryptionMask;
+ CPUID_MEMORY_ENCRYPTION_INFO_EBX Ebx;
+
+ if (mAddressEncMaskChecked) {
+ return mAddressEncMask;
+ }
+
+ //
+ // 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;
+}
+
+/**
+ Split 2M page to 4K.
+
+ @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 = AllocatePages(1);
+
+ PageTableEntry1 = PageTableEntry;
+
+ AddressEncMask = GetMemEncryptionAddressMask ();
+
+ ASSERT (PageTableEntry != NULL);
+ ASSERT (*PageEntry2M & AddressEncMask);
+
+ PhysicalAddress4K = PhysicalAddress;
+ 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)) {
+ //
+ // 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;
+}
+
+/**
+ Split 1G page to 2M.
+
+ @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 = AllocatePages(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;
+
+ PhysicalAddress2M = PhysicalAddress;
+ 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);
+ } 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
+
+**/
+STATIC VOID
+SetOrClearCBit(
+ IN OUT UINT64* PageTablePointer,
+ IN MAP_RANGE_MODE Mode
+ )
+{
+ UINT64 AddressEncMask;
+
+ AddressEncMask = GetMemEncryptionAddressMask ();
+
+ if (Mode == SetCBit) {
+ *PageTablePointer |= AddressEncMask;
+ } else {
+ *PageTablePointer &= ~AddressEncMask;
+ }
+
+}
+
+/**
+ 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_INVALID_PARAMETER Number of pages is zero.
+ @retval RETURN_UNSUPPORTED Setting the memory encyrption attribute is
+ not supported
+**/
+
+STATIC
+EFI_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;
+ UINT64 AddressEncMask;
+
+ //
+ // 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 EFI_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
+ //
+ if (CacheFlush) {
+ WriteBackInvalidateDataCacheRange((VOID*) (UINTN)PhysicalAddress, Length);
+ }
+
+ 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_WARN, "ERROR bad PML4 for %lx\n", PhysicalAddress));
+ return EFI_NO_MAPPING;
+ }
+
+ PageDirectory1GEntry = (VOID*) ((PageMapLevel4Entry->Bits.PageTableBaseAddress<<12) & ~PgTableMask);
+ PageDirectory1GEntry += PDP_OFFSET(PhysicalAddress);
+ if (!PageDirectory1GEntry->Bits.Present) {
+ DEBUG ((DEBUG_WARN, "ERROR bad PDPE for %lx\n", PhysicalAddress));
+ return EFI_NO_MAPPING;
+ }
+
+ //
+ // 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
+ //
+ if (!(PhysicalAddress & (BIT30 - 1)) && Length >= BIT30) {
+ SetOrClearCBit(&PageDirectory1GEntry->Uint64, Mode);
+ DEBUG ((DEBUG_VERBOSE, "Updated 1GB entry for %lx\n", PhysicalAddress));
+ PhysicalAddress += BIT30;
+ Length -= BIT30;
+ } else {
+ //
+ // We must split the page
+ //
+ DEBUG ((DEBUG_VERBOSE, "Spliting 1GB page\n"));
+ 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);
+ PageDirectory2MEntry += PDE_OFFSET(PhysicalAddress);
+ if (!PageDirectory2MEntry->Bits.Present) {
+ DEBUG ((DEBUG_WARN, "ERROR bad PDE for %lx\n", PhysicalAddress));
+ return EFI_NO_MAPPING;
+ }
+ //
+ // 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);
+ DEBUG ((DEBUG_VERBOSE, "Updated 2MB entry for %lx\n", PhysicalAddress));
+ PhysicalAddress += BIT21;
+ Length -= BIT21;
+ } else {
+ //
+ // We must split up this page into 4K pages
+ //
+ DEBUG ((DEBUG_VERBOSE, "Spliting 2MB page at %lx\n", PhysicalAddress));
+ 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);
+ PageTableEntry += PTE_OFFSET(PhysicalAddress);
+ if (!PageTableEntry->Bits.Present) {
+ DEBUG ((DEBUG_WARN, "ERROR bad PTE for %lx\n", PhysicalAddress));
+ return EFI_NO_MAPPING;
+ }
+ SetOrClearCBit (&PageTableEntry->Uint64, Mode);
+ DEBUG ((DEBUG_VERBOSE, "Updated 4KB entry for %lx\n", PhysicalAddress));
+ PhysicalAddress += EFI_PAGE_SIZE;
+ Length -= EFI_PAGE_SIZE;
+ }
+ }
+ }
+
+ //
+ // Flush TLB
+ //
+ CpuFlushTlb();
+
+ return EFI_SUCCESS;
+}
+
+/**
+ 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_INVALID_PARAMETER Number of pages is zero.
+ @retval RETURN_UNSUPPORTED Setting the memory encyrption attribute is
+ not supported
+**/
+EFI_STATUS
+EFIAPI
+SetMemoryDecrypted (
+ IN PHYSICAL_ADDRESS Cr3BaseAddress,
+ IN PHYSICAL_ADDRESS PhysicalAddress,
+ IN UINTN Length,
+ IN BOOLEAN CacheFlush
+ )
+{
+
+ DEBUG ((DEBUG_VERBOSE, "Clear C-bit Base %Lx Length %Lx flush %d\n", PhysicalAddress, Length, CacheFlush));
+ return SetMemoryEncDec (Cr3BaseAddress, PhysicalAddress, Length, ClearCBit, 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] 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
+**/
+EFI_STATUS
+EFIAPI
+SetMemoryEncrypted (
+ IN PHYSICAL_ADDRESS Cr3BaseAddress,
+ IN PHYSICAL_ADDRESS PhysicalAddress,
+ IN UINTN Length,
+ IN BOOLEAN CacheFlush
+ )
+{
+ DEBUG ((DEBUG_VERBOSE, "Set C-bit Base %Lx Length %Lx flush %d\n", PhysicalAddress, Length, CacheFlush));
+ return SetMemoryEncDec (Cr3BaseAddress, PhysicalAddress, Length, SetCBit, CacheFlush);
+}
--
2.7.4
^ permalink raw reply related [flat|nested] 42+ messages in thread
* Re: [RFC v4 04/13] OvmfPkg/BaseMemcryptSevLib: Add SEV helper library
2017-05-10 22:09 ` [RFC v4 04/13] OvmfPkg/BaseMemcryptSevLib: Add SEV helper library Brijesh Singh
@ 2017-05-11 14:04 ` Laszlo Ersek
2017-05-11 18:03 ` Brijesh Singh
0 siblings, 1 reply; 42+ messages in thread
From: Laszlo Ersek @ 2017-05-11 14:04 UTC (permalink / raw)
To: Brijesh Singh, edk2-devel; +Cc: Thomas.Lendacky, leo.duran, Jordan Justen
On 05/11/17 00:09, Brijesh Singh wrote:
> Add Secure Encrypted Virtualization (SEV) helper library.
> The library provides the routines to:
> - set or clear memory encryption bit for a given memory region.
> - query whether SEV is enabled.
>
>
> Cc: Jordan Justen <jordan.l.justen@intel.com>
> Cc: Laszlo Ersek <lersek@redhat.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
> ---
> OvmfPkg/OvmfPkgIa32.dsc | 1 +
> OvmfPkg/OvmfPkgIa32X64.dsc | 1 +
> OvmfPkg/OvmfPkgX64.dsc | 1 +
> OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf | 50 +++
> OvmfPkg/Include/Library/MemEncryptSevLib.h | 81 ++++
> OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.h | 34 ++
> OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h | 184 +++++++++
> OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c | 126 ++++++
> OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c | 43 ++
> OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c | 127 ++++++
> OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c | 422 ++++++++++++++++++++
> 11 files changed, 1070 insertions(+)
I have the following suggestions for this patch:
(1) The InternalMemEncryptSevIsEnabled() function is identical between
"Ia32/MemEncryptSevLib.c" and "X64/MemEncryptSevLib.c". In addition,
that function is the only one exported by "MemEncryptSevLibInternal.h".
I suggest to eliminate "MemEncryptSevLibInternal.h", and to move the
common implementation of InternalMemEncryptSevIsEnabled() into
"MemEncryptSevLibInternal.c". The moved function should be made STATIC.
This decreases code duplication and removes an internal header file.
(2) Please prefix the names of the extern functions SetMemoryDecrypted()
and SetMemoryEncrypted() with "InternalMemEncryptSev".
(3) Since this is a BASE library, please don't use EFI_STATUS,
EFI_INVALID_PARAMETER, EFI_NO_MAPPING, EFI_SUCCESS; use RETURN_xxx instead.
(4) Since this library is going to be linked into multiple modules
(presumably), please consider modifying all the debug messages as
follows: the format strings should start with "%a: %a: ", and the
arguments to pass in should be gEfiCallerBaseName and __FUNCTION__.
The former arg will make the library print the BASE_NAME of the
containing driver module (from its INF). And __FUNCTION__ helps jumping
to the location more quickly.
With those changes:
Reviewed-by: Laszlo Ersek <lersek@redhat.com>
Thanks
Laszlo
> diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc
> index 6494ac5480b3..265f2d2b6d2f 100644
> --- a/OvmfPkg/OvmfPkgIa32.dsc
> +++ b/OvmfPkg/OvmfPkgIa32.dsc
> @@ -143,6 +143,7 @@ [LibraryClasses]
> QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
> VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf
> LoadLinuxLib|OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.inf
> + MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
> !if $(SMM_REQUIRE) == FALSE
> LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf
> !endif
> diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
> index 20eb409a8d01..3b50a2dd2d2f 100644
> --- a/OvmfPkg/OvmfPkgIa32X64.dsc
> +++ b/OvmfPkg/OvmfPkgIa32X64.dsc
> @@ -148,6 +148,7 @@ [LibraryClasses]
> QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
> VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf
> LoadLinuxLib|OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.inf
> + MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
> !if $(SMM_REQUIRE) == FALSE
> LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf
> !endif
> diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
> index 2e5eaf631e9f..82c73331aa9f 100644
> --- a/OvmfPkg/OvmfPkgX64.dsc
> +++ b/OvmfPkg/OvmfPkgX64.dsc
> @@ -148,6 +148,7 @@ [LibraryClasses]
> QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
> VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf
> LoadLinuxLib|OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.inf
> + MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
> !if $(SMM_REQUIRE) == FALSE
> LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf
> !endif
> diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf b/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
> new file mode 100644
> index 000000000000..949c430af61b
> --- /dev/null
> +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
> @@ -0,0 +1,50 @@
> +## @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.
> +#
> +#
> +##
> +
> +[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
> + OvmfPkg/OvmfPkg.dec
> + UefiCpuPkg/UefiCpuPkg.dec
> +
> +[Sources.X64]
> + X64/MemEncryptSevLib.c
> + X64/VirtualMemory.c
> + MemEncryptSevLibInternal.c
> +
> +[Sources.IA32]
> + Ia32/MemEncryptSevLib.c
> + MemEncryptSevLibInternal.c
> +
> +[LibraryClasses]
> + BaseLib
> + CpuLib
> + CacheMaintenanceLib
> + DebugLib
> + MemoryAllocationLib
> diff --git a/OvmfPkg/Include/Library/MemEncryptSevLib.h b/OvmfPkg/Include/Library/MemEncryptSevLib.h
> new file mode 100644
> index 000000000000..b6753762423e
> --- /dev/null
> +++ b/OvmfPkg/Include/Library/MemEncryptSevLib.h
> @@ -0,0 +1,81 @@
> +/** @file
> +
> + Define Secure Encrypted Virtualization (SEV) base 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.
> +
> +**/
> +
> +#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 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.
> + @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] 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
> +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/MemEncryptSevLibInternal.h b/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.h
> new file mode 100644
> index 000000000000..17f67b47dbee
> --- /dev/null
> +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.h
> @@ -0,0 +1,34 @@
> +/** @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.
> +
> +**/
> +
> +#ifndef _MEM_ENCRYPT_SEV_LIB_INTERNAL_H_
> +#define _MEM_ENCRYPT_SEV_LIB_INTERNAL_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
> +InternalMemEncryptSevIsEnabled (
> + VOID
> + );
> +
> +#endif
> diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h
> new file mode 100644
> index 000000000000..ab5a6ddc3e85
> --- /dev/null
> +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.h
> @@ -0,0 +1,184 @@
> +/** @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.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 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)
> + 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 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)
> + 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 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
> + } 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 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)
> + 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 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
> + } 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 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)
> + 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 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
> + } Bits;
> + UINT64 Uint64;
> +} PAGE_TABLE_1G_ENTRY;
> +
> +#pragma pack()
> +
> +#define IA32_PG_P BIT0
> +#define IA32_PG_RW BIT1
> +
> +#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
> +
> +/**
> + 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_INVALID_PARAMETER Number of pages is zero.
> + @retval RETURN_UNSUPPORTED Setting the memory encyrption attribute is not supported
> +**/
> +EFI_STATUS
> +EFIAPI
> +SetMemoryDecrypted (
> + 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] 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
> +**/
> +EFI_STATUS
> +EFIAPI
> +SetMemoryEncrypted (
> + 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
> new file mode 100644
> index 000000000000..4b7f421475ac
> --- /dev/null
> +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/Ia32/MemEncryptSevLib.c
> @@ -0,0 +1,126 @@
> +/** @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 "Uefi.h"
> +#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 "MemEncryptSevLibInternal.h"
> +
> +/**
> +
> + Returns a boolean to indicate whether SEV is enabled
> +
> + @retval TRUE SEV is enabled
> + @retval FALSE SEV is not enabled
> + **/
> +BOOLEAN
> +EFIAPI
> +InternalMemEncryptSevIsEnabled (
> + VOID
> + )
> +{
> + UINT32 RegEax;
> + MSR_SEV_STATUS_REGISTER Msr;
> + CPUID_MEMORY_ENCRYPTION_INFO_EAX Eax;
> +
> + //
> + // Check if memory encryption leaf exist
> + //
> + AsmCpuid (CPUID_EXTENDED_FUNCTION, &RegEax, NULL, NULL, NULL);
> + if (RegEax >= CPUID_MEMORY_ENCRYPTION_INFO) {
> + //
> + // 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 is Enabled)
> + //
> + Msr.Uint32 = AsmReadMsr32 (MSR_SEV_STATUS);
> + if (Msr.Bits.SevBit) {
> + return TRUE;
> + }
> + }
> + }
> +
> + return FALSE;
> +}
> +
> +/**
> + 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.
> + @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] 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
> +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
> new file mode 100644
> index 000000000000..43ecba7a28bb
> --- /dev/null
> +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/MemEncryptSevLibInternal.c
> @@ -0,0 +1,43 @@
> +/** @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 "MemEncryptSevLibInternal.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
> + **/
> +BOOLEAN
> +EFIAPI
> +MemEncryptSevIsEnabled (
> + VOID
> + )
> +{
> + if (mSevStatusChecked) {
> + return mSevStatus;
> + }
> +
> + mSevStatus = InternalMemEncryptSevIsEnabled();
> + mSevStatusChecked = TRUE;
> +
> + return mSevStatus;
> +}
> diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c
> new file mode 100644
> index 000000000000..92f701497ffb
> --- /dev/null
> +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/MemEncryptSevLib.c
> @@ -0,0 +1,127 @@
> +/** @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 "Uefi.h"
> +#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"
> +#include "MemEncryptSevLibInternal.h"
> +
> +/**
> +
> + Returns a boolean to indicate whether SEV is enabled
> +
> + @retval TRUE SEV is enabled
> + @retval FALSE SEV is not enabled
> + **/
> +BOOLEAN
> +EFIAPI
> +InternalMemEncryptSevIsEnabled (
> + VOID
> + )
> +{
> + UINT32 RegEax;
> + MSR_SEV_STATUS_REGISTER Msr;
> + CPUID_MEMORY_ENCRYPTION_INFO_EAX Eax;
> +
> + //
> + // Check if memory encryption leaf exist
> + //
> + AsmCpuid (CPUID_EXTENDED_FUNCTION, &RegEax, NULL, NULL, NULL);
> + if (RegEax >= CPUID_MEMORY_ENCRYPTION_INFO) {
> + //
> + // 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;
> +}
> +
> +/**
> +
> + 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] 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 SetMemoryDecrypted (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] 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
> +MemEncryptSevSetPageEncMask (
> + IN PHYSICAL_ADDRESS Cr3BaseAddress,
> + IN PHYSICAL_ADDRESS BaseAddress,
> + IN UINTN NumPages,
> + IN BOOLEAN Flush
> + )
> +{
> + return SetMemoryEncrypted (Cr3BaseAddress, BaseAddress, EFI_PAGES_TO_SIZE(NumPages), Flush);
> +}
> diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
> new file mode 100644
> index 000000000000..51425830baa5
> --- /dev/null
> +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/VirtualMemory.c
> @@ -0,0 +1,422 @@
> +/** @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 "VirtualMemory.h"
> +
> +STATIC BOOLEAN mAddressEncMaskChecked = FALSE;
> +STATIC UINT64 mAddressEncMask;
> +
> +typedef enum {
> + SetCBit,
> + ClearCBit
> +} MAP_RANGE_MODE;
> +
> +/**
> + Get the memory encryption mask
> +
> + @param[out] EncryptionMask contains the pte mask.
> +
> +**/
> +STATIC
> +UINT64
> +GetMemEncryptionAddressMask (
> + VOID
> + )
> +{
> + UINT64 EncryptionMask;
> + CPUID_MEMORY_ENCRYPTION_INFO_EBX Ebx;
> +
> + if (mAddressEncMaskChecked) {
> + return mAddressEncMask;
> + }
> +
> + //
> + // 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;
> +}
> +
> +/**
> + Split 2M page to 4K.
> +
> + @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 = AllocatePages(1);
> +
> + PageTableEntry1 = PageTableEntry;
> +
> + AddressEncMask = GetMemEncryptionAddressMask ();
> +
> + ASSERT (PageTableEntry != NULL);
> + ASSERT (*PageEntry2M & AddressEncMask);
> +
> + PhysicalAddress4K = PhysicalAddress;
> + 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)) {
> + //
> + // 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;
> +}
> +
> +/**
> + Split 1G page to 2M.
> +
> + @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 = AllocatePages(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;
> +
> + PhysicalAddress2M = PhysicalAddress;
> + 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);
> + } 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
> +
> +**/
> +STATIC VOID
> +SetOrClearCBit(
> + IN OUT UINT64* PageTablePointer,
> + IN MAP_RANGE_MODE Mode
> + )
> +{
> + UINT64 AddressEncMask;
> +
> + AddressEncMask = GetMemEncryptionAddressMask ();
> +
> + if (Mode == SetCBit) {
> + *PageTablePointer |= AddressEncMask;
> + } else {
> + *PageTablePointer &= ~AddressEncMask;
> + }
> +
> +}
> +
> +/**
> + 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_INVALID_PARAMETER Number of pages is zero.
> + @retval RETURN_UNSUPPORTED Setting the memory encyrption attribute is
> + not supported
> +**/
> +
> +STATIC
> +EFI_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;
> + UINT64 AddressEncMask;
> +
> + //
> + // 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 EFI_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
> + //
> + if (CacheFlush) {
> + WriteBackInvalidateDataCacheRange((VOID*) (UINTN)PhysicalAddress, Length);
> + }
> +
> + 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_WARN, "ERROR bad PML4 for %lx\n", PhysicalAddress));
> + return EFI_NO_MAPPING;
> + }
> +
> + PageDirectory1GEntry = (VOID*) ((PageMapLevel4Entry->Bits.PageTableBaseAddress<<12) & ~PgTableMask);
> + PageDirectory1GEntry += PDP_OFFSET(PhysicalAddress);
> + if (!PageDirectory1GEntry->Bits.Present) {
> + DEBUG ((DEBUG_WARN, "ERROR bad PDPE for %lx\n", PhysicalAddress));
> + return EFI_NO_MAPPING;
> + }
> +
> + //
> + // 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
> + //
> + if (!(PhysicalAddress & (BIT30 - 1)) && Length >= BIT30) {
> + SetOrClearCBit(&PageDirectory1GEntry->Uint64, Mode);
> + DEBUG ((DEBUG_VERBOSE, "Updated 1GB entry for %lx\n", PhysicalAddress));
> + PhysicalAddress += BIT30;
> + Length -= BIT30;
> + } else {
> + //
> + // We must split the page
> + //
> + DEBUG ((DEBUG_VERBOSE, "Spliting 1GB page\n"));
> + 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);
> + PageDirectory2MEntry += PDE_OFFSET(PhysicalAddress);
> + if (!PageDirectory2MEntry->Bits.Present) {
> + DEBUG ((DEBUG_WARN, "ERROR bad PDE for %lx\n", PhysicalAddress));
> + return EFI_NO_MAPPING;
> + }
> + //
> + // 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);
> + DEBUG ((DEBUG_VERBOSE, "Updated 2MB entry for %lx\n", PhysicalAddress));
> + PhysicalAddress += BIT21;
> + Length -= BIT21;
> + } else {
> + //
> + // We must split up this page into 4K pages
> + //
> + DEBUG ((DEBUG_VERBOSE, "Spliting 2MB page at %lx\n", PhysicalAddress));
> + 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);
> + PageTableEntry += PTE_OFFSET(PhysicalAddress);
> + if (!PageTableEntry->Bits.Present) {
> + DEBUG ((DEBUG_WARN, "ERROR bad PTE for %lx\n", PhysicalAddress));
> + return EFI_NO_MAPPING;
> + }
> + SetOrClearCBit (&PageTableEntry->Uint64, Mode);
> + DEBUG ((DEBUG_VERBOSE, "Updated 4KB entry for %lx\n", PhysicalAddress));
> + PhysicalAddress += EFI_PAGE_SIZE;
> + Length -= EFI_PAGE_SIZE;
> + }
> + }
> + }
> +
> + //
> + // Flush TLB
> + //
> + CpuFlushTlb();
> +
> + return EFI_SUCCESS;
> +}
> +
> +/**
> + 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_INVALID_PARAMETER Number of pages is zero.
> + @retval RETURN_UNSUPPORTED Setting the memory encyrption attribute is
> + not supported
> +**/
> +EFI_STATUS
> +EFIAPI
> +SetMemoryDecrypted (
> + IN PHYSICAL_ADDRESS Cr3BaseAddress,
> + IN PHYSICAL_ADDRESS PhysicalAddress,
> + IN UINTN Length,
> + IN BOOLEAN CacheFlush
> + )
> +{
> +
> + DEBUG ((DEBUG_VERBOSE, "Clear C-bit Base %Lx Length %Lx flush %d\n", PhysicalAddress, Length, CacheFlush));
> + return SetMemoryEncDec (Cr3BaseAddress, PhysicalAddress, Length, ClearCBit, 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] 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
> +**/
> +EFI_STATUS
> +EFIAPI
> +SetMemoryEncrypted (
> + IN PHYSICAL_ADDRESS Cr3BaseAddress,
> + IN PHYSICAL_ADDRESS PhysicalAddress,
> + IN UINTN Length,
> + IN BOOLEAN CacheFlush
> + )
> +{
> + DEBUG ((DEBUG_VERBOSE, "Set C-bit Base %Lx Length %Lx flush %d\n", PhysicalAddress, Length, CacheFlush));
> + return SetMemoryEncDec (Cr3BaseAddress, PhysicalAddress, Length, SetCBit, CacheFlush);
> +}
>
^ permalink raw reply [flat|nested] 42+ messages in thread
* Re: [RFC v4 04/13] OvmfPkg/BaseMemcryptSevLib: Add SEV helper library
2017-05-11 14:04 ` Laszlo Ersek
@ 2017-05-11 18:03 ` Brijesh Singh
0 siblings, 0 replies; 42+ messages in thread
From: Brijesh Singh @ 2017-05-11 18:03 UTC (permalink / raw)
To: Laszlo Ersek, edk2-devel
Cc: brijesh.singh, Thomas.Lendacky, leo.duran, Jordan Justen
On 05/11/2017 09:04 AM, Laszlo Ersek wrote:
>
> I have the following suggestions for this patch:
>
> (1) The InternalMemEncryptSevIsEnabled() function is identical between
> "Ia32/MemEncryptSevLib.c" and "X64/MemEncryptSevLib.c". In addition,
> that function is the only one exported by "MemEncryptSevLibInternal.h".
>
> I suggest to eliminate "MemEncryptSevLibInternal.h", and to move the
> common implementation of InternalMemEncryptSevIsEnabled() into
> "MemEncryptSevLibInternal.c". The moved function should be made STATIC.
>
> This decreases code duplication and removes an internal header file.
>
> (2) Please prefix the names of the extern functions SetMemoryDecrypted()
> and SetMemoryEncrypted() with "InternalMemEncryptSev".
>
> (3) Since this is a BASE library, please don't use EFI_STATUS,
> EFI_INVALID_PARAMETER, EFI_NO_MAPPING, EFI_SUCCESS; use RETURN_xxx instead.
>
> (4) Since this library is going to be linked into multiple modules
> (presumably), please consider modifying all the debug messages as
> follows: the format strings should start with "%a: %a: ", and the
> arguments to pass in should be gEfiCallerBaseName and __FUNCTION__.
>
> The former arg will make the library print the BASE_NAME of the
> containing driver module (from its INF). And __FUNCTION__ helps jumping
> to the location more quickly.
I was not aware of built-in gEfiCallerBaseName, it will be really handy.
I agree with all your comments and will update the patch to remove the
code duplication.
-Brijesh
^ permalink raw reply [flat|nested] 42+ messages in thread
* [RFC v4 05/13] OvmfPkg/PlatformPei: Set memory encryption PCD when SEV is enabled
2017-05-10 22:09 [RFC v4 00/13] x86: Secure Encrypted Virtualization (AMD) Brijesh Singh
` (3 preceding siblings ...)
2017-05-10 22:09 ` [RFC v4 04/13] OvmfPkg/BaseMemcryptSevLib: Add SEV helper library Brijesh Singh
@ 2017-05-10 22:09 ` Brijesh Singh
2017-05-11 14:37 ` Laszlo Ersek
2017-05-10 22:09 ` [RFC v4 06/13] OvmfPkg:AmdSevDxe: add AmdSevDxe driver Brijesh Singh
` (7 subsequent siblings)
12 siblings, 1 reply; 42+ messages in thread
From: Brijesh Singh @ 2017-05-10 22:09 UTC (permalink / raw)
To: edk2-devel
Cc: Thomas.Lendacky, leo.duran, Brijesh Singh, Jordan Justen,
Laszlo Ersek
Secure Encrypted Virtualization (SEV) guest VMs have the concept of
private and shared memory. Private memory is encrypted with the
guest-specific key, while shared memory may be encrypted with hypervisor
key. Certain types of memory (namely instruction pages and guest page
tables) are always treated as private memory by the hardware.
For data memory, SEV guest VMs can choose which pages they would like
to be private. The choice is done using the standard CPU page tables
using the C-bit. When building the initial page table we mark all the
memory as private.
The patch sets the memory encryption PCD, the PCD is used by DxeCore
when building the initial page table.
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
---
OvmfPkg/OvmfPkgIa32.dsc | 3 +
OvmfPkg/OvmfPkgIa32X64.dsc | 3 +
OvmfPkg/OvmfPkgX64.dsc | 3 +
OvmfPkg/PlatformPei/PlatformPei.inf | 3 +
OvmfPkg/PlatformPei/Platform.h | 5 ++
OvmfPkg/PlatformPei/AmdSev.c | 62 ++++++++++++++++++++
OvmfPkg/PlatformPei/Platform.c | 1 +
7 files changed, 80 insertions(+)
diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc
index 265f2d2b6d2f..139d54aa010e 100644
--- a/OvmfPkg/OvmfPkgIa32.dsc
+++ b/OvmfPkg/OvmfPkgIa32.dsc
@@ -530,6 +530,9 @@ [PcdsDynamicDefault]
gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64
gUefiCpuPkgTokenSpaceGuid.PcdCpuApInitTimeOutInMicroSeconds|50000
+ # Set memory encryption mask
+ gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask|0x0
+
!if $(SMM_REQUIRE) == TRUE
gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmSyncMode|0x01
gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmApSyncTimeout|100000
diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
index 3b50a2dd2d2f..9403f76ce862 100644
--- a/OvmfPkg/OvmfPkgIa32X64.dsc
+++ b/OvmfPkg/OvmfPkgIa32X64.dsc
@@ -538,6 +538,9 @@ [PcdsDynamicDefault]
gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64
gUefiCpuPkgTokenSpaceGuid.PcdCpuApInitTimeOutInMicroSeconds|50000
+ # Set memory encryption mask
+ gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask|0x0
+
!if $(SMM_REQUIRE) == TRUE
gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmSyncMode|0x01
gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmApSyncTimeout|100000
diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
index 82c73331aa9f..e137143f7afa 100644
--- a/OvmfPkg/OvmfPkgX64.dsc
+++ b/OvmfPkg/OvmfPkgX64.dsc
@@ -537,6 +537,9 @@ [PcdsDynamicDefault]
gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64
gUefiCpuPkgTokenSpaceGuid.PcdCpuApInitTimeOutInMicroSeconds|50000
+ # Set memory encryption mask
+ gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask|0x0
+
!if $(SMM_REQUIRE) == TRUE
gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmSyncMode|0x01
gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmApSyncTimeout|100000
diff --git a/OvmfPkg/PlatformPei/PlatformPei.inf b/OvmfPkg/PlatformPei/PlatformPei.inf
index 53c6dd445a0e..a9a7a76c7325 100644
--- a/OvmfPkg/PlatformPei/PlatformPei.inf
+++ b/OvmfPkg/PlatformPei/PlatformPei.inf
@@ -29,6 +29,7 @@ [Defines]
#
[Sources]
+ AmdSev.c
Cmos.c
FeatureControl.c
Fv.c
@@ -60,6 +61,7 @@ [LibraryClasses]
QemuFwCfgLib
QemuFwCfgS3Lib
MtrrLib
+ MemEncryptSevLib
PcdLib
[Pcd]
@@ -94,6 +96,7 @@ [Pcd]
gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack
gEfiMdeModulePkgTokenSpaceGuid.PcdPropertiesTableEnable
gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiS3Enable
+ gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask
gUefiCpuPkgTokenSpaceGuid.PcdCpuLocalApicBaseAddress
gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber
gUefiCpuPkgTokenSpaceGuid.PcdCpuApInitTimeOutInMicroSeconds
diff --git a/OvmfPkg/PlatformPei/Platform.h b/OvmfPkg/PlatformPei/Platform.h
index 18f42c3f0ea8..a7729b9df44b 100644
--- a/OvmfPkg/PlatformPei/Platform.h
+++ b/OvmfPkg/PlatformPei/Platform.h
@@ -88,6 +88,11 @@ XenDetect (
VOID
);
+VOID
+AmdSevInitialize (
+ VOID
+ );
+
extern BOOLEAN mXen;
VOID
diff --git a/OvmfPkg/PlatformPei/AmdSev.c b/OvmfPkg/PlatformPei/AmdSev.c
new file mode 100644
index 000000000000..26f7c3fdbb13
--- /dev/null
+++ b/OvmfPkg/PlatformPei/AmdSev.c
@@ -0,0 +1,62 @@
+/**@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/PcdLib.h>
+#include <Register/Cpuid.h>
+#include <Register/Amd/Cpuid.h>
+#include <Library/MemEncryptSevLib.h>
+
+/**
+
+ Function checks if SEV support is available, if present then it sets
+ the dynamic PcdPteMemoryEncryptionAddressOrMask with memory encryption mask.
+
+ **/
+VOID
+EFIAPI
+AmdSevInitialize (
+ VOID
+ )
+{
+ CPUID_MEMORY_ENCRYPTION_INFO_EBX Ebx;
+ UINT64 EncryptionMask;
+ RETURN_STATUS PcdStatus;
+
+ //
+ // Check if SEV is enabled
+ //
+ if (!MemEncryptSevIsEnabled ()) {
+ return;
+ }
+
+ //
+ // 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));
+}
diff --git a/OvmfPkg/PlatformPei/Platform.c b/OvmfPkg/PlatformPei/Platform.c
index 5e983a8dcea9..5121e337bdcb 100644
--- a/OvmfPkg/PlatformPei/Platform.c
+++ b/OvmfPkg/PlatformPei/Platform.c
@@ -678,6 +678,7 @@ InitializePlatform (
NoexecDxeInitialization ();
}
+ AmdSevInitialize ();
MiscInitialization ();
InstallFeatureControlCallback ();
--
2.7.4
^ permalink raw reply related [flat|nested] 42+ messages in thread
* Re: [RFC v4 05/13] OvmfPkg/PlatformPei: Set memory encryption PCD when SEV is enabled
2017-05-10 22:09 ` [RFC v4 05/13] OvmfPkg/PlatformPei: Set memory encryption PCD when SEV is enabled Brijesh Singh
@ 2017-05-11 14:37 ` Laszlo Ersek
2017-05-11 18:04 ` Brijesh Singh
0 siblings, 1 reply; 42+ messages in thread
From: Laszlo Ersek @ 2017-05-11 14:37 UTC (permalink / raw)
To: Brijesh Singh, edk2-devel; +Cc: Thomas.Lendacky, leo.duran, Jordan Justen
On 05/11/17 00:09, Brijesh Singh wrote:
> Secure Encrypted Virtualization (SEV) guest VMs have the concept of
> private and shared memory. Private memory is encrypted with the
> guest-specific key, while shared memory may be encrypted with hypervisor
> key. Certain types of memory (namely instruction pages and guest page
> tables) are always treated as private memory by the hardware.
> For data memory, SEV guest VMs can choose which pages they would like
> to be private. The choice is done using the standard CPU page tables
> using the C-bit. When building the initial page table we mark all the
> memory as private.
>
> The patch sets the memory encryption PCD, the PCD is used by DxeCore
> when building the initial page table.
Please replace the last paragraph in the commit message with the
following (mostly based on
<http://mid.mail-archive.com/ec83b052-1af7-c985-35a3-0838c5943add@redhat.com>):
----
The patch sets the memory encryption PCD. The PCD is consumed by the
following edk2 modules, which manipulate page tables:
- PEI phase modules: CapsulePei, DxeIplPeim, S3Resume2Pei.
CapsulePei is not used by OVMF. DxeIplPeim consumes the PCD at the
end of the PEI phase, when it builds the initial page tables for the
DXE core / DXE phase. S3Resume2Pei does not consume the PCD in its
entry point function, only when DxeIplPeim branches to the S3 resume
path at the end of the PEI phase, and calls S3Resume2Pei's
EFI_PEI_S3_RESUME2_PPI.S3RestoreConfig2() member function.
Therefore it is safe to set the PCD for these modules in PlatformPei.
- DXE phase modules: BootScriptExecutorDxe, CpuDxe, PiSmmCpuDxeSmm.
They are all dispatched after the PEI phase, so setting the PCD for
them in PlatformPei is safe. (BootScriptExecutorDxe is launched "for
real" in the PEI phase during S3 resume, but it caches the PCD into a
static variable when its entry point is originally invoked in DXE.)
----
With that update,
Reviewed-by: Laszlo Ersek <lersek@redhat.com>
Thanks,
Laszlo
>
>
> Cc: Jordan Justen <jordan.l.justen@intel.com>
> Cc: Laszlo Ersek <lersek@redhat.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
> ---
> OvmfPkg/OvmfPkgIa32.dsc | 3 +
> OvmfPkg/OvmfPkgIa32X64.dsc | 3 +
> OvmfPkg/OvmfPkgX64.dsc | 3 +
> OvmfPkg/PlatformPei/PlatformPei.inf | 3 +
> OvmfPkg/PlatformPei/Platform.h | 5 ++
> OvmfPkg/PlatformPei/AmdSev.c | 62 ++++++++++++++++++++
> OvmfPkg/PlatformPei/Platform.c | 1 +
> 7 files changed, 80 insertions(+)
>
> diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc
> index 265f2d2b6d2f..139d54aa010e 100644
> --- a/OvmfPkg/OvmfPkgIa32.dsc
> +++ b/OvmfPkg/OvmfPkgIa32.dsc
> @@ -530,6 +530,9 @@ [PcdsDynamicDefault]
> gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64
> gUefiCpuPkgTokenSpaceGuid.PcdCpuApInitTimeOutInMicroSeconds|50000
>
> + # Set memory encryption mask
> + gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask|0x0
> +
> !if $(SMM_REQUIRE) == TRUE
> gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmSyncMode|0x01
> gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmApSyncTimeout|100000
> diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
> index 3b50a2dd2d2f..9403f76ce862 100644
> --- a/OvmfPkg/OvmfPkgIa32X64.dsc
> +++ b/OvmfPkg/OvmfPkgIa32X64.dsc
> @@ -538,6 +538,9 @@ [PcdsDynamicDefault]
> gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64
> gUefiCpuPkgTokenSpaceGuid.PcdCpuApInitTimeOutInMicroSeconds|50000
>
> + # Set memory encryption mask
> + gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask|0x0
> +
> !if $(SMM_REQUIRE) == TRUE
> gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmSyncMode|0x01
> gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmApSyncTimeout|100000
> diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
> index 82c73331aa9f..e137143f7afa 100644
> --- a/OvmfPkg/OvmfPkgX64.dsc
> +++ b/OvmfPkg/OvmfPkgX64.dsc
> @@ -537,6 +537,9 @@ [PcdsDynamicDefault]
> gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64
> gUefiCpuPkgTokenSpaceGuid.PcdCpuApInitTimeOutInMicroSeconds|50000
>
> + # Set memory encryption mask
> + gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask|0x0
> +
> !if $(SMM_REQUIRE) == TRUE
> gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmSyncMode|0x01
> gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmApSyncTimeout|100000
> diff --git a/OvmfPkg/PlatformPei/PlatformPei.inf b/OvmfPkg/PlatformPei/PlatformPei.inf
> index 53c6dd445a0e..a9a7a76c7325 100644
> --- a/OvmfPkg/PlatformPei/PlatformPei.inf
> +++ b/OvmfPkg/PlatformPei/PlatformPei.inf
> @@ -29,6 +29,7 @@ [Defines]
> #
>
> [Sources]
> + AmdSev.c
> Cmos.c
> FeatureControl.c
> Fv.c
> @@ -60,6 +61,7 @@ [LibraryClasses]
> QemuFwCfgLib
> QemuFwCfgS3Lib
> MtrrLib
> + MemEncryptSevLib
> PcdLib
>
> [Pcd]
> @@ -94,6 +96,7 @@ [Pcd]
> gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack
> gEfiMdeModulePkgTokenSpaceGuid.PcdPropertiesTableEnable
> gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiS3Enable
> + gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask
> gUefiCpuPkgTokenSpaceGuid.PcdCpuLocalApicBaseAddress
> gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber
> gUefiCpuPkgTokenSpaceGuid.PcdCpuApInitTimeOutInMicroSeconds
> diff --git a/OvmfPkg/PlatformPei/Platform.h b/OvmfPkg/PlatformPei/Platform.h
> index 18f42c3f0ea8..a7729b9df44b 100644
> --- a/OvmfPkg/PlatformPei/Platform.h
> +++ b/OvmfPkg/PlatformPei/Platform.h
> @@ -88,6 +88,11 @@ XenDetect (
> VOID
> );
>
> +VOID
> +AmdSevInitialize (
> + VOID
> + );
> +
> extern BOOLEAN mXen;
>
> VOID
> diff --git a/OvmfPkg/PlatformPei/AmdSev.c b/OvmfPkg/PlatformPei/AmdSev.c
> new file mode 100644
> index 000000000000..26f7c3fdbb13
> --- /dev/null
> +++ b/OvmfPkg/PlatformPei/AmdSev.c
> @@ -0,0 +1,62 @@
> +/**@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/PcdLib.h>
> +#include <Register/Cpuid.h>
> +#include <Register/Amd/Cpuid.h>
> +#include <Library/MemEncryptSevLib.h>
> +
> +/**
> +
> + Function checks if SEV support is available, if present then it sets
> + the dynamic PcdPteMemoryEncryptionAddressOrMask with memory encryption mask.
> +
> + **/
> +VOID
> +EFIAPI
> +AmdSevInitialize (
> + VOID
> + )
> +{
> + CPUID_MEMORY_ENCRYPTION_INFO_EBX Ebx;
> + UINT64 EncryptionMask;
> + RETURN_STATUS PcdStatus;
> +
> + //
> + // Check if SEV is enabled
> + //
> + if (!MemEncryptSevIsEnabled ()) {
> + return;
> + }
> +
> + //
> + // 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));
> +}
> diff --git a/OvmfPkg/PlatformPei/Platform.c b/OvmfPkg/PlatformPei/Platform.c
> index 5e983a8dcea9..5121e337bdcb 100644
> --- a/OvmfPkg/PlatformPei/Platform.c
> +++ b/OvmfPkg/PlatformPei/Platform.c
> @@ -678,6 +678,7 @@ InitializePlatform (
> NoexecDxeInitialization ();
> }
>
> + AmdSevInitialize ();
> MiscInitialization ();
> InstallFeatureControlCallback ();
>
>
^ permalink raw reply [flat|nested] 42+ messages in thread
* Re: [RFC v4 05/13] OvmfPkg/PlatformPei: Set memory encryption PCD when SEV is enabled
2017-05-11 14:37 ` Laszlo Ersek
@ 2017-05-11 18:04 ` Brijesh Singh
0 siblings, 0 replies; 42+ messages in thread
From: Brijesh Singh @ 2017-05-11 18:04 UTC (permalink / raw)
To: Laszlo Ersek, edk2-devel
Cc: brijesh.singh, Thomas.Lendacky, leo.duran, Jordan Justen
On 05/11/2017 09:37 AM, Laszlo Ersek wrote:
>
> Please replace the last paragraph in the commit message with the
> following (mostly based on
> <http://mid.mail-archive.com/ec83b052-1af7-c985-35a3-0838c5943add@redhat.com>):
>
> ----
> The patch sets the memory encryption PCD. The PCD is consumed by the
> following edk2 modules, which manipulate page tables:
>
> - PEI phase modules: CapsulePei, DxeIplPeim, S3Resume2Pei.
>
> CapsulePei is not used by OVMF. DxeIplPeim consumes the PCD at the
> end of the PEI phase, when it builds the initial page tables for the
> DXE core / DXE phase. S3Resume2Pei does not consume the PCD in its
> entry point function, only when DxeIplPeim branches to the S3 resume
> path at the end of the PEI phase, and calls S3Resume2Pei's
> EFI_PEI_S3_RESUME2_PPI.S3RestoreConfig2() member function.
>
> Therefore it is safe to set the PCD for these modules in PlatformPei.
>
> - DXE phase modules: BootScriptExecutorDxe, CpuDxe, PiSmmCpuDxeSmm.
>
> They are all dispatched after the PEI phase, so setting the PCD for
> them in PlatformPei is safe. (BootScriptExecutorDxe is launched "for
> real" in the PEI phase during S3 resume, but it caches the PCD into a
> static variable when its entry point is originally invoked in DXE.)
> ----
>
I will update the patch description, thanks for the write up.
-Brijesh
^ permalink raw reply [flat|nested] 42+ messages in thread
* [RFC v4 06/13] OvmfPkg:AmdSevDxe: add AmdSevDxe driver
2017-05-10 22:09 [RFC v4 00/13] x86: Secure Encrypted Virtualization (AMD) Brijesh Singh
` (4 preceding siblings ...)
2017-05-10 22:09 ` [RFC v4 05/13] OvmfPkg/PlatformPei: Set memory encryption PCD when SEV is enabled Brijesh Singh
@ 2017-05-10 22:09 ` Brijesh Singh
2017-05-11 0:56 ` Yao, Jiewen
2017-05-11 15:19 ` Laszlo Ersek
2017-05-10 22:09 ` [RFC v4 07/13] OvmfPkg/QemuFwCfgLib: Provide Pei and Dxe specific library Brijesh Singh
` (6 subsequent siblings)
12 siblings, 2 replies; 42+ messages in thread
From: Brijesh Singh @ 2017-05-10 22:09 UTC (permalink / raw)
To: edk2-devel
Cc: Thomas.Lendacky, leo.duran, Brijesh Singh, Jordan Justen,
Laszlo Ersek, Jiewen Yao
When SEV is enabled, the MMIO memory range must be mapped as unencrypted
(i.e C-bit cleared) and DMA must be performed on unencrypted memory.
The patch adds a DXE driver that runs early in boot and clears the memory
encryption attribute from MMIO/NonExistent memory ranges and installs a
IOMMU protocol to provide the DMA support for PCIHostBridge and other drivers.
The driver produces IOMMU protocol introduce by Jiewen
https://lists.01.org/pipermail/edk2-devel/2017-May/010462.html
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Cc: Leo Duran <leo.duran@amd.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
---
OvmfPkg/OvmfPkgIa32X64.dsc | 1 +
OvmfPkg/OvmfPkgX64.dsc | 1 +
OvmfPkg/OvmfPkgIa32X64.fdf | 2 +
OvmfPkg/OvmfPkgX64.fdf | 2 +
OvmfPkg/AmdSevDxe/AmdSevDxe.inf | 49 +++
OvmfPkg/AmdSevDxe/AmdSevIommu.h | 43 ++
OvmfPkg/AmdSevDxe/AmdSevMmio.h | 41 ++
OvmfPkg/AmdSevDxe/AmdSevDxe.c | 52 +++
OvmfPkg/AmdSevDxe/AmdSevIommu.c | 459 ++++++++++++++++++++
OvmfPkg/AmdSevDxe/AmdSevMmio.c | 50 +++
10 files changed, 700 insertions(+)
diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
index 9403f76ce862..ee6f98d68b73 100644
--- a/OvmfPkg/OvmfPkgIa32X64.dsc
+++ b/OvmfPkg/OvmfPkgIa32X64.dsc
@@ -827,6 +827,7 @@ [Components.X64]
!endif
OvmfPkg/PlatformDxe/Platform.inf
+ OvmfPkg/AmdSevDxe/AmdSevDxe.inf
!if $(SMM_REQUIRE) == TRUE
OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
index e137143f7afa..b5f26e06e60b 100644
--- a/OvmfPkg/OvmfPkgX64.dsc
+++ b/OvmfPkg/OvmfPkgX64.dsc
@@ -825,6 +825,7 @@ [Components]
!endif
OvmfPkg/PlatformDxe/Platform.inf
+ OvmfPkg/AmdSevDxe/AmdSevDxe.inf
!if $(SMM_REQUIRE) == TRUE
OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
diff --git a/OvmfPkg/OvmfPkgIa32X64.fdf b/OvmfPkg/OvmfPkgIa32X64.fdf
index 5233314139bc..12871860d001 100644
--- a/OvmfPkg/OvmfPkgIa32X64.fdf
+++ b/OvmfPkg/OvmfPkgIa32X64.fdf
@@ -190,6 +190,7 @@ [FV.DXEFV]
APRIORI DXE {
INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
INF MdeModulePkg/Universal/PCD/Dxe/Pcd.inf
+ INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf
!if $(SMM_REQUIRE) == FALSE
INF OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
!endif
@@ -351,6 +352,7 @@ [FV.DXEFV]
INF OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf
INF OvmfPkg/VirtioGpuDxe/VirtioGpu.inf
INF OvmfPkg/PlatformDxe/Platform.inf
+INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf
!if $(SMM_REQUIRE) == TRUE
INF OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
diff --git a/OvmfPkg/OvmfPkgX64.fdf b/OvmfPkg/OvmfPkgX64.fdf
index 36150101e784..ae6e66a1c08d 100644
--- a/OvmfPkg/OvmfPkgX64.fdf
+++ b/OvmfPkg/OvmfPkgX64.fdf
@@ -190,6 +190,7 @@ [FV.DXEFV]
APRIORI DXE {
INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
INF MdeModulePkg/Universal/PCD/Dxe/Pcd.inf
+ INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf
!if $(SMM_REQUIRE) == FALSE
INF OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
!endif
@@ -351,6 +352,7 @@ [FV.DXEFV]
INF OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf
INF OvmfPkg/VirtioGpuDxe/VirtioGpu.inf
INF OvmfPkg/PlatformDxe/Platform.inf
+INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf
!if $(SMM_REQUIRE) == TRUE
INF OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.inf b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
new file mode 100644
index 000000000000..775dda9be386
--- /dev/null
+++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
@@ -0,0 +1,49 @@
+#/** @file
+#
+# Driver clears the encryption attribute from MMIO regions and installs IOMMU
+# protcol to provides DMA support for PciHostBridge and others
+#
+# 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.
+#
+#**/
+
+[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
+ AmdSevIommu.c
+ AmdSevMmio.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ OvmfPkg/OvmfPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ UefiLib
+ UefiDriverEntryPoint
+ UefiBootServicesTableLib
+ DxeServicesTableLib
+ DebugLib
+ MemEncryptSevLib
+
+[Protocols]
+ gEdkiiIoMmuProtocolGuid ## PRODUCES
+
+[Depex]
+ TRUE
diff --git a/OvmfPkg/AmdSevDxe/AmdSevIommu.h b/OvmfPkg/AmdSevDxe/AmdSevIommu.h
new file mode 100644
index 000000000000..5712cb57052d
--- /dev/null
+++ b/OvmfPkg/AmdSevDxe/AmdSevIommu.h
@@ -0,0 +1,43 @@
+/** @file
+
+ The protocol provides support to allocate, free, map and umap a DMA buffer for
+ bus master (e.g PciHostBridge). When SEV is enabled, the DMA operations must
+ be performed on unencrypted buffer hence protocol clear the encryption bit
+ from the DMA buffer.
+
+ Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
+ 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.
+
+**/
+
+#ifndef __AMDSEVIOMMU_H_
+#define __AMDSEVIOMMU_H
+
+#include <Protocol/IoMmu.h>
+
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/MemEncryptSevLib.h>
+
+/**
+ Install IOMMU protocol to provide the DMA support for PciHostBridge and
+ MemEncryptSevLib.
+
+**/
+VOID
+EFIAPI
+AmdSevInstallIommuProtocol (
+ VOID
+ );
+
+#endif
diff --git a/OvmfPkg/AmdSevDxe/AmdSevMmio.h b/OvmfPkg/AmdSevDxe/AmdSevMmio.h
new file mode 100644
index 000000000000..c6191025d921
--- /dev/null
+++ b/OvmfPkg/AmdSevDxe/AmdSevMmio.h
@@ -0,0 +1,41 @@
+/** @file
+
+ Implements routines to clear C-bit from MMIO Memory Range
+
+ 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.
+
+**/
+
+#ifndef __AMDSEVMMIO_H_
+#define __AMDSEVMMIO_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>
+
+/**
+
+ 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 NonExistent
+ memory space can gurantee that any MMIO mapped later will have C-bit cleared.
+*/
+VOID
+EFIAPI
+AmdSevClearEncMaskMmioRange (
+ VOID
+ );
+
+#endif
diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.c b/OvmfPkg/AmdSevDxe/AmdSevDxe.c
new file mode 100644
index 000000000000..e22e7ef7314f
--- /dev/null
+++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.c
@@ -0,0 +1,52 @@
+/** @file
+
+ AMD Sev Dxe driver. The driver runs early in DXE phase and clears C-bit from
+ MMIO space and installs EDKII_IOMMU_PROTOCOL to provide the support for DMA
+ operations 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/MemEncryptSevLib.h>
+
+#include "AmdSevMmio.h"
+#include "AmdSevIommu.h"
+
+EFI_STATUS
+EFIAPI
+AmdSevDxeEntryPoint (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ //
+ // Do nothing when SEV is not enabled
+ //
+ if (!MemEncryptSevIsEnabled ()) {
+ return EFI_SUCCESS;
+ }
+
+ //
+ // Clear C-bit from MMIO Memory Range
+ //
+ AmdSevClearEncMaskMmioRange ();
+
+ //
+ // Install IOMMU protocol to provide DMA support for PCIHostBridgeIo and
+ // AmdSevMemEncryptLib.
+ //
+ AmdSevInstallIommuProtocol ();
+
+ return EFI_SUCCESS;
+}
diff --git a/OvmfPkg/AmdSevDxe/AmdSevIommu.c b/OvmfPkg/AmdSevDxe/AmdSevIommu.c
new file mode 100644
index 000000000000..9b35469ca34f
--- /dev/null
+++ b/OvmfPkg/AmdSevDxe/AmdSevIommu.c
@@ -0,0 +1,459 @@
+/** @file
+ AmdSevIommu related function
+
+ The protocol provides support to allocate, free, map and umap a DMA buffer for
+ bus master (e.g PciHostBridge). When SEV is enabled, the DMA operations must
+ be performed on unencrypted buffer hence we use a bounce buffer to map the host
+ buffer into an unencrypted buffer.
+
+ 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 "AmdSevIommu.h"
+
+typedef struct {
+ EDKII_IOMMU_OPERATION Operation;
+ UINTN NumberOfBytes;
+ UINTN NumberOfPages;
+ EFI_PHYSICAL_ADDRESS HostAddress;
+ EFI_PHYSICAL_ADDRESS DeviceAddress;
+} MAP_INFO;
+
+#define NO_MAPPING (VOID *) (UINTN) -1
+
+/**
+ Provides the controller-specific addresses required to access system memory from a
+ DMA bus master. On SEV guest, the DMA operations must be performed on shared
+ buffer hence we allocate a bounce buffer to map the HostAddress to a DeviceAddress.
+ The Encryption attribute is removed from the DeviceAddress buffer.
+
+ @param This The protocol instance pointer.
+ @param Operation Indicates if the bus master is going to read or
+ write to system memory.
+ @param HostAddress The system memory address to map to the PCI controller.
+ @param NumberOfBytes On input the number of bytes to map. On output
+ the number of bytes
+ that were mapped.
+ @param DeviceAddress The resulting map address for the bus master PCI
+ controller to use to
+ access the hosts HostAddress.
+ @param Mapping A resulting value to pass to Unmap().
+
+ @retval EFI_SUCCESS The range was mapped for the returned NumberOfBytes.
+ @retval EFI_UNSUPPORTED The HostAddress cannot be mapped as a common buffer.
+ @retval EFI_INVALID_PARAMETER One or more parameters are invalid.
+ @retval EFI_OUT_OF_RESOURCES The request could not be completed due to a lack
+ of resources.
+ @retval EFI_DEVICE_ERROR The system hardware could not map the requested address.
+
+**/
+EFI_STATUS
+EFIAPI
+IoMmuMap (
+ IN EDKII_IOMMU_PROTOCOL *This,
+ IN EDKII_IOMMU_OPERATION Operation,
+ IN VOID *HostAddress,
+ IN OUT UINTN *NumberOfBytes,
+ OUT EFI_PHYSICAL_ADDRESS *DeviceAddress,
+ OUT VOID **Mapping
+ )
+{
+ EFI_STATUS Status;
+ EFI_PHYSICAL_ADDRESS PhysicalAddress;
+ MAP_INFO *MapInfo;
+ EFI_PHYSICAL_ADDRESS DmaMemoryTop;
+ EFI_ALLOCATE_TYPE AllocateType;
+
+ if (HostAddress == NULL || NumberOfBytes == NULL || DeviceAddress == NULL ||
+ Mapping == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // Make sure that Operation is valid
+ //
+ if ((UINT32) Operation >= EdkiiIoMmuOperationMaximum) {
+ return EFI_INVALID_PARAMETER;
+ }
+ PhysicalAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) HostAddress;
+
+ DmaMemoryTop = (UINTN)-1;
+ AllocateType = AllocateAnyPages;
+
+ if (((Operation != EdkiiIoMmuOperationBusMasterRead64 &&
+ Operation != EdkiiIoMmuOperationBusMasterWrite64 &&
+ Operation != EdkiiIoMmuOperationBusMasterCommonBuffer64)) &&
+ ((PhysicalAddress + *NumberOfBytes) > SIZE_4GB)) {
+ //
+ // If the root bridge or the device cannot handle performing DMA above
+ // 4GB but any part of the DMA transfer being mapped is above 4GB, then
+ // map the DMA transfer to a buffer below 4GB.
+ //
+ DmaMemoryTop = SIZE_4GB - 1;
+ AllocateType = AllocateMaxAddress;
+
+ if (Operation == EdkiiIoMmuOperationBusMasterCommonBuffer ||
+ Operation == EdkiiIoMmuOperationBusMasterCommonBuffer64) {
+ //
+ // Common Buffer operations can not be remapped. If the common buffer
+ // if above 4GB, then it is not possible to generate a mapping, so return
+ // an error.
+ //
+ return EFI_UNSUPPORTED;
+ }
+ }
+
+ //
+ // CommandBuffer was allocated by us (AllocateBuffer) and is already in
+ // unencryted buffer so no need to create bounce buffer
+ //
+ if (Operation == EdkiiIoMmuOperationBusMasterCommonBuffer ||
+ Operation == EdkiiIoMmuOperationBusMasterCommonBuffer64) {
+ *Mapping = NO_MAPPING;
+ *DeviceAddress = PhysicalAddress;
+
+ return EFI_SUCCESS;
+ }
+
+ //
+ // Allocate a MAP_INFO structure to remember the mapping when Unmap() is
+ // called later.
+ //
+ MapInfo = AllocatePool (sizeof (MAP_INFO));
+ if (MapInfo == NULL) {
+ *NumberOfBytes = 0;
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ //
+ // Initialize the MAP_INFO structure
+ //
+ MapInfo->Operation = Operation;
+ MapInfo->NumberOfBytes = *NumberOfBytes;
+ MapInfo->NumberOfPages = EFI_SIZE_TO_PAGES (MapInfo->NumberOfBytes);
+ MapInfo->HostAddress = PhysicalAddress;
+ MapInfo->DeviceAddress = DmaMemoryTop;
+
+ //
+ // Allocate a buffer to map the transfer to.
+ //
+ Status = gBS->AllocatePages (
+ AllocateType,
+ EfiBootServicesData,
+ MapInfo->NumberOfPages,
+ &MapInfo->DeviceAddress
+ );
+ if (EFI_ERROR (Status)) {
+ FreePool (MapInfo);
+ *NumberOfBytes = 0;
+ return Status;
+ }
+
+ //
+ // Clear the memory encryption mask from the device buffer
+ //
+ Status = MemEncryptSevClearPageEncMask (0, MapInfo->DeviceAddress, MapInfo->NumberOfPages, TRUE);
+ ASSERT_EFI_ERROR(Status);
+
+ //
+ // If this is a read operation from the Bus Master's point of view,
+ // then copy the contents of the real buffer into the mapped buffer
+ // so the Bus Master can read the contents of the real buffer.
+ //
+ if (Operation == EdkiiIoMmuOperationBusMasterRead ||
+ Operation == EdkiiIoMmuOperationBusMasterRead64) {
+ CopyMem (
+ (VOID *) (UINTN) MapInfo->DeviceAddress,
+ (VOID *) (UINTN) MapInfo->HostAddress,
+ MapInfo->NumberOfBytes
+ );
+ }
+
+ //
+ // The DeviceAddress is the address of the maped buffer below 4GB
+ //
+ *DeviceAddress = MapInfo->DeviceAddress;
+
+ //
+ // Return a pointer to the MAP_INFO structure in Mapping
+ //
+ *Mapping = MapInfo;
+
+ DEBUG ((DEBUG_VERBOSE, "%a Host 0x%Lx Device 0x%Lx Pages 0x%Lx Bytes 0x%Lx\n",
+ __FUNCTION__, MapInfo->DeviceAddress, MapInfo->HostAddress,
+ MapInfo->NumberOfPages, MapInfo->NumberOfBytes));
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Completes the Map() operation and releases any corresponding resources.
+
+ @param This The protocol instance pointer.
+ @param Mapping The mapping value returned from Map().
+
+ @retval EFI_SUCCESS The range was unmapped.
+ @retval EFI_INVALID_PARAMETER Mapping is not a value that was returned by Map().
+ @retval EFI_DEVICE_ERROR The data was not committed to the target system memory.
+**/
+EFI_STATUS
+EFIAPI
+IoMmuUnmap (
+ IN EDKII_IOMMU_PROTOCOL *This,
+ IN VOID *Mapping
+ )
+{
+ MAP_INFO *MapInfo;
+ EFI_STATUS Status;
+
+ if (Mapping == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // See if the Map() operation associated with this Unmap() required a mapping
+ // buffer. If a mapping buffer was not required, then this function simply
+ // buffer. If a mapping buffer was not required, then this function simply
+ //
+ if (Mapping == NO_MAPPING) {
+ return EFI_SUCCESS;
+ }
+
+ MapInfo = (MAP_INFO *)Mapping;
+
+ //
+ // If this is a write operation from the Bus Master's point of view,
+ // then copy the contents of the mapped buffer into the real buffer
+ // so the processor can read the contents of the real buffer.
+ //
+ if (MapInfo->Operation == EdkiiIoMmuOperationBusMasterWrite ||
+ MapInfo->Operation == EdkiiIoMmuOperationBusMasterWrite64) {
+ CopyMem (
+ (VOID *) (UINTN) MapInfo->HostAddress,
+ (VOID *) (UINTN) MapInfo->DeviceAddress,
+ MapInfo->NumberOfBytes
+ );
+ }
+
+ DEBUG ((DEBUG_VERBOSE, "%a Host 0x%Lx Device 0x%Lx Pages 0x%Lx Bytes 0x%Lx\n",
+ __FUNCTION__, MapInfo->DeviceAddress, MapInfo->HostAddress,
+ MapInfo->NumberOfPages, MapInfo->NumberOfBytes));
+ //
+ // Restore the memory encryption mask
+ //
+ Status = MemEncryptSevSetPageEncMask (0, MapInfo->DeviceAddress, MapInfo->NumberOfPages, TRUE);
+ ASSERT_EFI_ERROR(Status);
+
+ //
+ // Free the mapped buffer and the MAP_INFO structure.
+ //
+ gBS->FreePages (MapInfo->DeviceAddress, MapInfo->NumberOfPages);
+ FreePool (Mapping);
+ return EFI_SUCCESS;
+}
+
+/**
+ Allocates pages that are suitable for an OperationBusMasterCommonBuffer or
+ OperationBusMasterCommonBuffer64 mapping.
+
+ @param This The protocol instance pointer.
+ @param Type This parameter is not used and must be ignored.
+ @param MemoryType The type of memory to allocate, EfiBootServicesData
+ or EfiRuntimeServicesData.
+ @param Pages The number of pages to allocate.
+ @param HostAddress A pointer to store the base system memory address
+ of the allocated range.
+ @param Attributes The requested bit mask of attributes for the allocated range.
+
+ @retval EFI_SUCCESS The requested memory pages were allocated.
+ @retval EFI_UNSUPPORTED Attributes is unsupported. The only legal attribute
+ bits are MEMORY_WRITE_COMBINE and MEMORY_CACHED.
+ @retval EFI_INVALID_PARAMETER One or more parameters are invalid.
+ @retval EFI_OUT_OF_RESOURCES The memory pages could not be allocated.
+
+**/
+EFI_STATUS
+EFIAPI
+IoMmuAllocateBuffer (
+ IN EDKII_IOMMU_PROTOCOL *This,
+ IN EFI_ALLOCATE_TYPE Type,
+ IN EFI_MEMORY_TYPE MemoryType,
+ IN UINTN Pages,
+ IN OUT VOID **HostAddress,
+ IN UINT64 Attributes
+ )
+{
+ EFI_STATUS Status;
+ EFI_PHYSICAL_ADDRESS PhysicalAddress;
+
+ //
+ // Validate Attributes
+ //
+ if ((Attributes & EDKII_IOMMU_ATTRIBUTE_INVALID_FOR_ALLOCATE_BUFFER) != 0) {
+ return EFI_UNSUPPORTED;
+ }
+
+ //
+ // Check for invalid inputs
+ //
+ if (HostAddress == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // The only valid memory types are EfiBootServicesData and
+ // EfiRuntimeServicesData
+ //
+ if (MemoryType != EfiBootServicesData &&
+ MemoryType != EfiRuntimeServicesData) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ PhysicalAddress = (UINTN)-1;
+ if ((Attributes & EDKII_IOMMU_ATTRIBUTE_DUAL_ADDRESS_CYCLE) == 0) {
+ //
+ // Limit allocations to memory below 4GB
+ //
+ PhysicalAddress = SIZE_4GB - 1;
+ }
+ Status = gBS->AllocatePages (
+ AllocateMaxAddress,
+ MemoryType,
+ Pages,
+ &PhysicalAddress
+ );
+ if (!EFI_ERROR (Status)) {
+ *HostAddress = (VOID *) (UINTN) PhysicalAddress;
+
+ //
+ // Clear memory encryption mask
+ //
+ Status = MemEncryptSevClearPageEncMask (0, PhysicalAddress, Pages, TRUE);
+ ASSERT_EFI_ERROR(Status);
+ }
+
+ DEBUG ((DEBUG_VERBOSE, "%a Address 0x%Lx Pages 0x%Lx\n", __FUNCTION__, PhysicalAddress, Pages));
+ return Status;
+}
+
+/**
+ Frees memory that was allocated with AllocateBuffer().
+
+ @param This The protocol instance pointer.
+ @param Pages The number of pages to free.
+ @param HostAddress The base system memory address of the allocated range.
+
+ @retval EFI_SUCCESS The requested memory pages were freed.
+ @retval EFI_INVALID_PARAMETER The memory range specified by HostAddress and Pages
+ was not allocated with AllocateBuffer().
+
+**/
+EFI_STATUS
+EFIAPI
+IoMmuFreeBuffer (
+ IN EDKII_IOMMU_PROTOCOL *This,
+ IN UINTN Pages,
+ IN VOID *HostAddress
+ )
+{
+ EFI_STATUS Status;
+
+ //
+ // Set memory encryption mask
+ //
+ Status = MemEncryptSevSetPageEncMask (0, (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress, Pages, TRUE);
+ ASSERT_EFI_ERROR(Status);
+
+ DEBUG ((DEBUG_VERBOSE, "%a Address 0x%Lx Pages 0x%Lx\n", __FUNCTION__, (UINTN)HostAddress, Pages));
+ return gBS->FreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) HostAddress, Pages);
+}
+
+
+/**
+ Set IOMMU attribute for a system memory.
+
+ If the IOMMU protocol exists, the system memory cannot be used
+ for DMA by default.
+
+ When a device requests a DMA access for a system memory,
+ the device driver need use SetAttribute() to update the IOMMU
+ attribute to request DMA access (read and/or write).
+
+ The DeviceHandle is used to identify which device submits the request.
+ The IOMMU implementation need translate the device path to an IOMMU device ID,
+ and set IOMMU hardware register accordingly.
+ 1) DeviceHandle can be a standard PCI device.
+ The memory for BusMasterRead need set EDKII_IOMMU_ACCESS_READ.
+ The memory for BusMasterWrite need set EDKII_IOMMU_ACCESS_WRITE.
+ The memory for BusMasterCommonBuffer need set EDKII_IOMMU_ACCESS_READ|EDKII_IOMMU_ACCESS_WRITE.
+ After the memory is used, the memory need set 0 to keep it being protected.
+ 2) DeviceHandle can be an ACPI device (ISA, I2C, SPI, etc).
+ The memory for DMA access need set EDKII_IOMMU_ACCESS_READ and/or EDKII_IOMMU_ACCESS_WRITE.
+
+ @param[in] This The protocol instance pointer.
+ @param[in] DeviceHandle The device who initiates the DMA access request.
+ @param[in] Mapping The mapping value returned from Map().
+ @param[in] IoMmuAccess The IOMMU access.
+
+ @retval EFI_SUCCESS The IoMmuAccess is set for the memory range specified by DeviceAddress and Length.
+ @retval EFI_INVALID_PARAMETER DeviceHandle is an invalid handle.
+ @retval EFI_INVALID_PARAMETER Mapping is not a value that was returned by Map().
+ @retval EFI_INVALID_PARAMETER IoMmuAccess specified an illegal combination of access.
+ @retval EFI_UNSUPPORTED DeviceHandle is unknown by the IOMMU.
+ @retval EFI_UNSUPPORTED The bit mask of IoMmuAccess is not supported by the IOMMU.
+ @retval EFI_UNSUPPORTED The IOMMU does not support the memory range specified by Mapping.
+ @retval EFI_OUT_OF_RESOURCES There are not enough resources available to modify the IOMMU access.
+ @retval EFI_DEVICE_ERROR The IOMMU device reported an error while attempting the operation.
+
+**/
+EFI_STATUS
+EFIAPI
+IoMmuSetAttribute (
+ IN EDKII_IOMMU_PROTOCOL *This,
+ IN EFI_HANDLE DeviceHandle,
+ IN VOID *Mapping,
+ IN UINT64 IoMmuAccess
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+EDKII_IOMMU_PROTOCOL mAmdSev = {
+ EDKII_IOMMU_PROTOCOL_REVISION,
+ IoMmuSetAttribute,
+ IoMmuMap,
+ IoMmuUnmap,
+ IoMmuAllocateBuffer,
+ IoMmuFreeBuffer,
+};
+
+/**
+ Initialize Iommu Protocol.
+
+**/
+VOID
+EFIAPI
+AmdSevInstallIommuProtocol (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ EFI_HANDLE Handle;
+
+ Handle = NULL;
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &Handle,
+ &gEdkiiIoMmuProtocolGuid, &mAmdSev,
+ NULL
+ );
+ ASSERT_EFI_ERROR (Status);
+}
diff --git a/OvmfPkg/AmdSevDxe/AmdSevMmio.c b/OvmfPkg/AmdSevDxe/AmdSevMmio.c
new file mode 100644
index 000000000000..b623f82b7baa
--- /dev/null
+++ b/OvmfPkg/AmdSevDxe/AmdSevMmio.c
@@ -0,0 +1,50 @@
+/** @file
+
+ Implements routines to clear C-bit from MMIO Memory Range
+
+ 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 "AmdSevMmio.h"
+
+/**
+
+ 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 NonExistent
+ memory space can gurantee that any MMIO mapped later will have C-bit cleared.
+*/
+VOID
+EFIAPI
+AmdSevClearEncMaskMmioRange (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ EFI_GCD_MEMORY_SPACE_DESCRIPTOR *AllDescMap;
+ UINTN NumEntries;
+ UINTN Index;
+
+ Status = gDS->GetMemorySpaceMap (&NumEntries, &AllDescMap);
+ if (Status == EFI_SUCCESS) {
+ 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);
+ }
+ }
+ }
+}
--
2.7.4
^ permalink raw reply related [flat|nested] 42+ messages in thread
* Re: [RFC v4 06/13] OvmfPkg:AmdSevDxe: add AmdSevDxe driver
2017-05-10 22:09 ` [RFC v4 06/13] OvmfPkg:AmdSevDxe: add AmdSevDxe driver Brijesh Singh
@ 2017-05-11 0:56 ` Yao, Jiewen
2017-05-11 15:19 ` Laszlo Ersek
1 sibling, 0 replies; 42+ messages in thread
From: Yao, Jiewen @ 2017-05-11 0:56 UTC (permalink / raw)
To: Brijesh Singh, edk2-devel@lists.01.org
Cc: Thomas.Lendacky@amd.com, Justen, Jordan L, leo.duran@amd.com,
Laszlo Ersek
Thanks!
Reviewed-by: Jiewen.yao@intel.com
Thank you
Yao Jiewen
> -----Original Message-----
> From: edk2-devel [mailto:edk2-devel-bounces@lists.01.org] On Behalf Of Brijesh
> Singh
> Sent: Thursday, May 11, 2017 6:09 AM
> To: edk2-devel@lists.01.org
> Cc: Thomas.Lendacky@amd.com; Justen, Jordan L <jordan.l.justen@intel.com>;
> Yao, Jiewen <jiewen.yao@intel.com>; leo.duran@amd.com; Laszlo Ersek
> <lersek@redhat.com>
> Subject: [edk2] [RFC v4 06/13] OvmfPkg:AmdSevDxe: add AmdSevDxe driver
>
> When SEV is enabled, the MMIO memory range must be mapped as
> unencrypted
> (i.e C-bit cleared) and DMA must be performed on unencrypted memory.
>
> The patch adds a DXE driver that runs early in boot and clears the memory
> encryption attribute from MMIO/NonExistent memory ranges and installs a
> IOMMU protocol to provide the DMA support for PCIHostBridge and other
> drivers.
>
> The driver produces IOMMU protocol introduce by Jiewen
> https://lists.01.org/pipermail/edk2-devel/2017-May/010462.html
>
>
> Cc: Jordan Justen <jordan.l.justen@intel.com>
> Cc: Laszlo Ersek <lersek@redhat.com>
> Cc: Leo Duran <leo.duran@amd.com>
> Cc: Jiewen Yao <jiewen.yao@intel.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
> ---
> OvmfPkg/OvmfPkgIa32X64.dsc | 1 +
> OvmfPkg/OvmfPkgX64.dsc | 1 +
> OvmfPkg/OvmfPkgIa32X64.fdf | 2 +
> OvmfPkg/OvmfPkgX64.fdf | 2 +
> OvmfPkg/AmdSevDxe/AmdSevDxe.inf | 49 +++
> OvmfPkg/AmdSevDxe/AmdSevIommu.h | 43 ++
> OvmfPkg/AmdSevDxe/AmdSevMmio.h | 41 ++
> OvmfPkg/AmdSevDxe/AmdSevDxe.c | 52 +++
> OvmfPkg/AmdSevDxe/AmdSevIommu.c | 459 ++++++++++++++++++++
> OvmfPkg/AmdSevDxe/AmdSevMmio.c | 50 +++
> 10 files changed, 700 insertions(+)
>
> diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
> index 9403f76ce862..ee6f98d68b73 100644
> --- a/OvmfPkg/OvmfPkgIa32X64.dsc
> +++ b/OvmfPkg/OvmfPkgIa32X64.dsc
> @@ -827,6 +827,7 @@ [Components.X64]
> !endif
>
> OvmfPkg/PlatformDxe/Platform.inf
> + OvmfPkg/AmdSevDxe/AmdSevDxe.inf
>
> !if $(SMM_REQUIRE) == TRUE
> OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
> diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
> index e137143f7afa..b5f26e06e60b 100644
> --- a/OvmfPkg/OvmfPkgX64.dsc
> +++ b/OvmfPkg/OvmfPkgX64.dsc
> @@ -825,6 +825,7 @@ [Components]
> !endif
>
> OvmfPkg/PlatformDxe/Platform.inf
> + OvmfPkg/AmdSevDxe/AmdSevDxe.inf
>
> !if $(SMM_REQUIRE) == TRUE
> OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
> diff --git a/OvmfPkg/OvmfPkgIa32X64.fdf b/OvmfPkg/OvmfPkgIa32X64.fdf
> index 5233314139bc..12871860d001 100644
> --- a/OvmfPkg/OvmfPkgIa32X64.fdf
> +++ b/OvmfPkg/OvmfPkgIa32X64.fdf
> @@ -190,6 +190,7 @@ [FV.DXEFV]
> APRIORI DXE {
> INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
> INF MdeModulePkg/Universal/PCD/Dxe/Pcd.inf
> + INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf
> !if $(SMM_REQUIRE) == FALSE
> INF
> OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
> !endif
> @@ -351,6 +352,7 @@ [FV.DXEFV]
> INF OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf
> INF OvmfPkg/VirtioGpuDxe/VirtioGpu.inf
> INF OvmfPkg/PlatformDxe/Platform.inf
> +INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf
>
> !if $(SMM_REQUIRE) == TRUE
> INF OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
> diff --git a/OvmfPkg/OvmfPkgX64.fdf b/OvmfPkg/OvmfPkgX64.fdf
> index 36150101e784..ae6e66a1c08d 100644
> --- a/OvmfPkg/OvmfPkgX64.fdf
> +++ b/OvmfPkg/OvmfPkgX64.fdf
> @@ -190,6 +190,7 @@ [FV.DXEFV]
> APRIORI DXE {
> INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
> INF MdeModulePkg/Universal/PCD/Dxe/Pcd.inf
> + INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf
> !if $(SMM_REQUIRE) == FALSE
> INF
> OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
> !endif
> @@ -351,6 +352,7 @@ [FV.DXEFV]
> INF OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf
> INF OvmfPkg/VirtioGpuDxe/VirtioGpu.inf
> INF OvmfPkg/PlatformDxe/Platform.inf
> +INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf
>
> !if $(SMM_REQUIRE) == TRUE
> INF OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
> diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
> b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
> new file mode 100644
> index 000000000000..775dda9be386
> --- /dev/null
> +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
> @@ -0,0 +1,49 @@
> +#/** @file
> +#
> +# Driver clears the encryption attribute from MMIO regions and installs
> IOMMU
> +# protcol to provides DMA support for PciHostBridge and others
> +#
> +# 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.
> +#
> +#**/
> +
> +[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
> + AmdSevIommu.c
> + AmdSevMmio.c
> +
> +[Packages]
> + MdePkg/MdePkg.dec
> + MdeModulePkg/MdeModulePkg.dec
> + OvmfPkg/OvmfPkg.dec
> +
> +[LibraryClasses]
> + BaseLib
> + UefiLib
> + UefiDriverEntryPoint
> + UefiBootServicesTableLib
> + DxeServicesTableLib
> + DebugLib
> + MemEncryptSevLib
> +
> +[Protocols]
> + gEdkiiIoMmuProtocolGuid ## PRODUCES
> +
> +[Depex]
> + TRUE
> diff --git a/OvmfPkg/AmdSevDxe/AmdSevIommu.h
> b/OvmfPkg/AmdSevDxe/AmdSevIommu.h
> new file mode 100644
> index 000000000000..5712cb57052d
> --- /dev/null
> +++ b/OvmfPkg/AmdSevDxe/AmdSevIommu.h
> @@ -0,0 +1,43 @@
> +/** @file
> +
> + The protocol provides support to allocate, free, map and umap a DMA buffer
> for
> + bus master (e.g PciHostBridge). When SEV is enabled, the DMA operations
> must
> + be performed on unencrypted buffer hence protocol clear the encryption bit
> + from the DMA buffer.
> +
> + Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
> + 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.
> +
> +**/
> +
> +#ifndef __AMDSEVIOMMU_H_
> +#define __AMDSEVIOMMU_H
> +
> +#include <Protocol/IoMmu.h>
> +
> +#include <Library/BaseLib.h>
> +#include <Library/DebugLib.h>
> +#include <Library/BaseMemoryLib.h>
> +#include <Library/MemoryAllocationLib.h>
> +#include <Library/UefiBootServicesTableLib.h>
> +#include <Library/MemEncryptSevLib.h>
> +
> +/**
> + Install IOMMU protocol to provide the DMA support for PciHostBridge and
> + MemEncryptSevLib.
> +
> +**/
> +VOID
> +EFIAPI
> +AmdSevInstallIommuProtocol (
> + VOID
> + );
> +
> +#endif
> diff --git a/OvmfPkg/AmdSevDxe/AmdSevMmio.h
> b/OvmfPkg/AmdSevDxe/AmdSevMmio.h
> new file mode 100644
> index 000000000000..c6191025d921
> --- /dev/null
> +++ b/OvmfPkg/AmdSevDxe/AmdSevMmio.h
> @@ -0,0 +1,41 @@
> +/** @file
> +
> + Implements routines to clear C-bit from MMIO Memory Range
> +
> + 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.
> +
> +**/
> +
> +#ifndef __AMDSEVMMIO_H_
> +#define __AMDSEVMMIO_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>
> +
> +/**
> +
> + 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 NonExistent
> + memory space can gurantee that any MMIO mapped later will have C-bit
> cleared.
> +*/
> +VOID
> +EFIAPI
> +AmdSevClearEncMaskMmioRange (
> + VOID
> + );
> +
> +#endif
> diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.c
> b/OvmfPkg/AmdSevDxe/AmdSevDxe.c
> new file mode 100644
> index 000000000000..e22e7ef7314f
> --- /dev/null
> +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.c
> @@ -0,0 +1,52 @@
> +/** @file
> +
> + AMD Sev Dxe driver. The driver runs early in DXE phase and clears C-bit from
> + MMIO space and installs EDKII_IOMMU_PROTOCOL to provide the support
> for DMA
> + operations 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/MemEncryptSevLib.h>
> +
> +#include "AmdSevMmio.h"
> +#include "AmdSevIommu.h"
> +
> +EFI_STATUS
> +EFIAPI
> +AmdSevDxeEntryPoint (
> + IN EFI_HANDLE ImageHandle,
> + IN EFI_SYSTEM_TABLE *SystemTable
> + )
> +{
> + //
> + // Do nothing when SEV is not enabled
> + //
> + if (!MemEncryptSevIsEnabled ()) {
> + return EFI_SUCCESS;
> + }
> +
> + //
> + // Clear C-bit from MMIO Memory Range
> + //
> + AmdSevClearEncMaskMmioRange ();
> +
> + //
> + // Install IOMMU protocol to provide DMA support for PCIHostBridgeIo and
> + // AmdSevMemEncryptLib.
> + //
> + AmdSevInstallIommuProtocol ();
> +
> + return EFI_SUCCESS;
> +}
> diff --git a/OvmfPkg/AmdSevDxe/AmdSevIommu.c
> b/OvmfPkg/AmdSevDxe/AmdSevIommu.c
> new file mode 100644
> index 000000000000..9b35469ca34f
> --- /dev/null
> +++ b/OvmfPkg/AmdSevDxe/AmdSevIommu.c
> @@ -0,0 +1,459 @@
> +/** @file
> + AmdSevIommu related function
> +
> + The protocol provides support to allocate, free, map and umap a DMA buffer
> for
> + bus master (e.g PciHostBridge). When SEV is enabled, the DMA operations
> must
> + be performed on unencrypted buffer hence we use a bounce buffer to map
> the host
> + buffer into an unencrypted buffer.
> +
> + 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 "AmdSevIommu.h"
> +
> +typedef struct {
> + EDKII_IOMMU_OPERATION Operation;
> + UINTN NumberOfBytes;
> + UINTN NumberOfPages;
> + EFI_PHYSICAL_ADDRESS HostAddress;
> + EFI_PHYSICAL_ADDRESS DeviceAddress;
> +} MAP_INFO;
> +
> +#define NO_MAPPING (VOID *) (UINTN) -1
> +
> +/**
> + Provides the controller-specific addresses required to access system memory
> from a
> + DMA bus master. On SEV guest, the DMA operations must be performed on
> shared
> + buffer hence we allocate a bounce buffer to map the HostAddress to a
> DeviceAddress.
> + The Encryption attribute is removed from the DeviceAddress buffer.
> +
> + @param This The protocol instance pointer.
> + @param Operation Indicates if the bus master is going to
> read or
> + write to system memory.
> + @param HostAddress The system memory address to map to
> the PCI controller.
> + @param NumberOfBytes On input the number of bytes to map.
> On output
> + the number of bytes
> + that were mapped.
> + @param DeviceAddress The resulting map address for the bus
> master PCI
> + controller to use to
> + access the hosts HostAddress.
> + @param Mapping A resulting value to pass to Unmap().
> +
> + @retval EFI_SUCCESS The range was mapped for the returned
> NumberOfBytes.
> + @retval EFI_UNSUPPORTED The HostAddress cannot be mapped as a
> common buffer.
> + @retval EFI_INVALID_PARAMETER One or more parameters are invalid.
> + @retval EFI_OUT_OF_RESOURCES The request could not be completed due
> to a lack
> + of resources.
> + @retval EFI_DEVICE_ERROR The system hardware could not map the
> requested address.
> +
> +**/
> +EFI_STATUS
> +EFIAPI
> +IoMmuMap (
> + IN EDKII_IOMMU_PROTOCOL *This,
> + IN EDKII_IOMMU_OPERATION Operation,
> + IN VOID *HostAddress,
> + IN OUT UINTN *NumberOfBytes,
> + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress,
> + OUT VOID **Mapping
> + )
> +{
> + EFI_STATUS Status;
> + EFI_PHYSICAL_ADDRESS PhysicalAddress;
> + MAP_INFO *MapInfo;
> + EFI_PHYSICAL_ADDRESS DmaMemoryTop;
> + EFI_ALLOCATE_TYPE AllocateType;
> +
> + if (HostAddress == NULL || NumberOfBytes == NULL || DeviceAddress ==
> NULL ||
> + Mapping == NULL) {
> + return EFI_INVALID_PARAMETER;
> + }
> +
> + //
> + // Make sure that Operation is valid
> + //
> + if ((UINT32) Operation >= EdkiiIoMmuOperationMaximum) {
> + return EFI_INVALID_PARAMETER;
> + }
> + PhysicalAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) HostAddress;
> +
> + DmaMemoryTop = (UINTN)-1;
> + AllocateType = AllocateAnyPages;
> +
> + if (((Operation != EdkiiIoMmuOperationBusMasterRead64 &&
> + Operation != EdkiiIoMmuOperationBusMasterWrite64 &&
> + Operation != EdkiiIoMmuOperationBusMasterCommonBuffer64)) &&
> + ((PhysicalAddress + *NumberOfBytes) > SIZE_4GB)) {
> + //
> + // If the root bridge or the device cannot handle performing DMA above
> + // 4GB but any part of the DMA transfer being mapped is above 4GB, then
> + // map the DMA transfer to a buffer below 4GB.
> + //
> + DmaMemoryTop = SIZE_4GB - 1;
> + AllocateType = AllocateMaxAddress;
> +
> + if (Operation == EdkiiIoMmuOperationBusMasterCommonBuffer ||
> + Operation == EdkiiIoMmuOperationBusMasterCommonBuffer64) {
> + //
> + // Common Buffer operations can not be remapped. If the common
> buffer
> + // if above 4GB, then it is not possible to generate a mapping, so
> return
> + // an error.
> + //
> + return EFI_UNSUPPORTED;
> + }
> + }
> +
> + //
> + // CommandBuffer was allocated by us (AllocateBuffer) and is already in
> + // unencryted buffer so no need to create bounce buffer
> + //
> + if (Operation == EdkiiIoMmuOperationBusMasterCommonBuffer ||
> + Operation == EdkiiIoMmuOperationBusMasterCommonBuffer64) {
> + *Mapping = NO_MAPPING;
> + *DeviceAddress = PhysicalAddress;
> +
> + return EFI_SUCCESS;
> + }
> +
> + //
> + // Allocate a MAP_INFO structure to remember the mapping when Unmap()
> is
> + // called later.
> + //
> + MapInfo = AllocatePool (sizeof (MAP_INFO));
> + if (MapInfo == NULL) {
> + *NumberOfBytes = 0;
> + return EFI_OUT_OF_RESOURCES;
> + }
> +
> + //
> + // Initialize the MAP_INFO structure
> + //
> + MapInfo->Operation = Operation;
> + MapInfo->NumberOfBytes = *NumberOfBytes;
> + MapInfo->NumberOfPages = EFI_SIZE_TO_PAGES
> (MapInfo->NumberOfBytes);
> + MapInfo->HostAddress = PhysicalAddress;
> + MapInfo->DeviceAddress = DmaMemoryTop;
> +
> + //
> + // Allocate a buffer to map the transfer to.
> + //
> + Status = gBS->AllocatePages (
> + AllocateType,
> + EfiBootServicesData,
> + MapInfo->NumberOfPages,
> + &MapInfo->DeviceAddress
> + );
> + if (EFI_ERROR (Status)) {
> + FreePool (MapInfo);
> + *NumberOfBytes = 0;
> + return Status;
> + }
> +
> + //
> + // Clear the memory encryption mask from the device buffer
> + //
> + Status = MemEncryptSevClearPageEncMask (0, MapInfo->DeviceAddress,
> MapInfo->NumberOfPages, TRUE);
> + ASSERT_EFI_ERROR(Status);
> +
> + //
> + // If this is a read operation from the Bus Master's point of view,
> + // then copy the contents of the real buffer into the mapped buffer
> + // so the Bus Master can read the contents of the real buffer.
> + //
> + if (Operation == EdkiiIoMmuOperationBusMasterRead ||
> + Operation == EdkiiIoMmuOperationBusMasterRead64) {
> + CopyMem (
> + (VOID *) (UINTN) MapInfo->DeviceAddress,
> + (VOID *) (UINTN) MapInfo->HostAddress,
> + MapInfo->NumberOfBytes
> + );
> + }
> +
> + //
> + // The DeviceAddress is the address of the maped buffer below 4GB
> + //
> + *DeviceAddress = MapInfo->DeviceAddress;
> +
> + //
> + // Return a pointer to the MAP_INFO structure in Mapping
> + //
> + *Mapping = MapInfo;
> +
> + DEBUG ((DEBUG_VERBOSE, "%a Host 0x%Lx Device 0x%Lx Pages 0x%Lx Bytes
> 0x%Lx\n",
> + __FUNCTION__, MapInfo->DeviceAddress, MapInfo->HostAddress,
> + MapInfo->NumberOfPages, MapInfo->NumberOfBytes));
> +
> + return EFI_SUCCESS;
> +}
> +
> +/**
> + Completes the Map() operation and releases any corresponding resources.
> +
> + @param This The protocol instance pointer.
> + @param Mapping The mapping value returned from
> Map().
> +
> + @retval EFI_SUCCESS The range was unmapped.
> + @retval EFI_INVALID_PARAMETER Mapping is not a value that was returned
> by Map().
> + @retval EFI_DEVICE_ERROR The data was not committed to the target
> system memory.
> +**/
> +EFI_STATUS
> +EFIAPI
> +IoMmuUnmap (
> + IN EDKII_IOMMU_PROTOCOL *This,
> + IN VOID *Mapping
> + )
> +{
> + MAP_INFO *MapInfo;
> + EFI_STATUS Status;
> +
> + if (Mapping == NULL) {
> + return EFI_INVALID_PARAMETER;
> + }
> +
> + //
> + // See if the Map() operation associated with this Unmap() required a
> mapping
> + // buffer. If a mapping buffer was not required, then this function simply
> + // buffer. If a mapping buffer was not required, then this function simply
> + //
> + if (Mapping == NO_MAPPING) {
> + return EFI_SUCCESS;
> + }
> +
> + MapInfo = (MAP_INFO *)Mapping;
> +
> + //
> + // If this is a write operation from the Bus Master's point of view,
> + // then copy the contents of the mapped buffer into the real buffer
> + // so the processor can read the contents of the real buffer.
> + //
> + if (MapInfo->Operation == EdkiiIoMmuOperationBusMasterWrite ||
> + MapInfo->Operation == EdkiiIoMmuOperationBusMasterWrite64) {
> + CopyMem (
> + (VOID *) (UINTN) MapInfo->HostAddress,
> + (VOID *) (UINTN) MapInfo->DeviceAddress,
> + MapInfo->NumberOfBytes
> + );
> + }
> +
> + DEBUG ((DEBUG_VERBOSE, "%a Host 0x%Lx Device 0x%Lx Pages 0x%Lx Bytes
> 0x%Lx\n",
> + __FUNCTION__, MapInfo->DeviceAddress, MapInfo->HostAddress,
> + MapInfo->NumberOfPages, MapInfo->NumberOfBytes));
> + //
> + // Restore the memory encryption mask
> + //
> + Status = MemEncryptSevSetPageEncMask (0, MapInfo->DeviceAddress,
> MapInfo->NumberOfPages, TRUE);
> + ASSERT_EFI_ERROR(Status);
> +
> + //
> + // Free the mapped buffer and the MAP_INFO structure.
> + //
> + gBS->FreePages (MapInfo->DeviceAddress, MapInfo->NumberOfPages);
> + FreePool (Mapping);
> + return EFI_SUCCESS;
> +}
> +
> +/**
> + Allocates pages that are suitable for an OperationBusMasterCommonBuffer
> or
> + OperationBusMasterCommonBuffer64 mapping.
> +
> + @param This The protocol instance pointer.
> + @param Type This parameter is not used and must be
> ignored.
> + @param MemoryType The type of memory to allocate,
> EfiBootServicesData
> + or EfiRuntimeServicesData.
> + @param Pages The number of pages to allocate.
> + @param HostAddress A pointer to store the base system
> memory address
> + of the allocated range.
> + @param Attributes The requested bit mask of attributes for
> the allocated range.
> +
> + @retval EFI_SUCCESS The requested memory pages were
> allocated.
> + @retval EFI_UNSUPPORTED Attributes is unsupported. The only legal
> attribute
> + bits are MEMORY_WRITE_COMBINE and
> MEMORY_CACHED.
> + @retval EFI_INVALID_PARAMETER One or more parameters are invalid.
> + @retval EFI_OUT_OF_RESOURCES The memory pages could not be
> allocated.
> +
> +**/
> +EFI_STATUS
> +EFIAPI
> +IoMmuAllocateBuffer (
> + IN EDKII_IOMMU_PROTOCOL *This,
> + IN EFI_ALLOCATE_TYPE Type,
> + IN EFI_MEMORY_TYPE MemoryType,
> + IN UINTN Pages,
> + IN OUT VOID **HostAddress,
> + IN UINT64 Attributes
> + )
> +{
> + EFI_STATUS Status;
> + EFI_PHYSICAL_ADDRESS PhysicalAddress;
> +
> + //
> + // Validate Attributes
> + //
> + if ((Attributes &
> EDKII_IOMMU_ATTRIBUTE_INVALID_FOR_ALLOCATE_BUFFER) != 0) {
> + return EFI_UNSUPPORTED;
> + }
> +
> + //
> + // Check for invalid inputs
> + //
> + if (HostAddress == NULL) {
> + return EFI_INVALID_PARAMETER;
> + }
> +
> + //
> + // The only valid memory types are EfiBootServicesData and
> + // EfiRuntimeServicesData
> + //
> + if (MemoryType != EfiBootServicesData &&
> + MemoryType != EfiRuntimeServicesData) {
> + return EFI_INVALID_PARAMETER;
> + }
> +
> + PhysicalAddress = (UINTN)-1;
> + if ((Attributes & EDKII_IOMMU_ATTRIBUTE_DUAL_ADDRESS_CYCLE) == 0) {
> + //
> + // Limit allocations to memory below 4GB
> + //
> + PhysicalAddress = SIZE_4GB - 1;
> + }
> + Status = gBS->AllocatePages (
> + AllocateMaxAddress,
> + MemoryType,
> + Pages,
> + &PhysicalAddress
> + );
> + if (!EFI_ERROR (Status)) {
> + *HostAddress = (VOID *) (UINTN) PhysicalAddress;
> +
> + //
> + // Clear memory encryption mask
> + //
> + Status = MemEncryptSevClearPageEncMask (0, PhysicalAddress, Pages,
> TRUE);
> + ASSERT_EFI_ERROR(Status);
> + }
> +
> + DEBUG ((DEBUG_VERBOSE, "%a Address 0x%Lx Pages 0x%Lx\n",
> __FUNCTION__, PhysicalAddress, Pages));
> + return Status;
> +}
> +
> +/**
> + Frees memory that was allocated with AllocateBuffer().
> +
> + @param This The protocol instance pointer.
> + @param Pages The number of pages to free.
> + @param HostAddress The base system memory address of the
> allocated range.
> +
> + @retval EFI_SUCCESS The requested memory pages were freed.
> + @retval EFI_INVALID_PARAMETER The memory range specified by
> HostAddress and Pages
> + was not allocated with AllocateBuffer().
> +
> +**/
> +EFI_STATUS
> +EFIAPI
> +IoMmuFreeBuffer (
> + IN EDKII_IOMMU_PROTOCOL *This,
> + IN UINTN Pages,
> + IN VOID *HostAddress
> + )
> +{
> + EFI_STATUS Status;
> +
> + //
> + // Set memory encryption mask
> + //
> + Status = MemEncryptSevSetPageEncMask (0,
> (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress, Pages, TRUE);
> + ASSERT_EFI_ERROR(Status);
> +
> + DEBUG ((DEBUG_VERBOSE, "%a Address 0x%Lx Pages 0x%Lx\n",
> __FUNCTION__, (UINTN)HostAddress, Pages));
> + return gBS->FreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) HostAddress,
> Pages);
> +}
> +
> +
> +/**
> + Set IOMMU attribute for a system memory.
> +
> + If the IOMMU protocol exists, the system memory cannot be used
> + for DMA by default.
> +
> + When a device requests a DMA access for a system memory,
> + the device driver need use SetAttribute() to update the IOMMU
> + attribute to request DMA access (read and/or write).
> +
> + The DeviceHandle is used to identify which device submits the request.
> + The IOMMU implementation need translate the device path to an IOMMU
> device ID,
> + and set IOMMU hardware register accordingly.
> + 1) DeviceHandle can be a standard PCI device.
> + The memory for BusMasterRead need set EDKII_IOMMU_ACCESS_READ.
> + The memory for BusMasterWrite need set
> EDKII_IOMMU_ACCESS_WRITE.
> + The memory for BusMasterCommonBuffer need set
> EDKII_IOMMU_ACCESS_READ|EDKII_IOMMU_ACCESS_WRITE.
> + After the memory is used, the memory need set 0 to keep it being
> protected.
> + 2) DeviceHandle can be an ACPI device (ISA, I2C, SPI, etc).
> + The memory for DMA access need set EDKII_IOMMU_ACCESS_READ
> and/or EDKII_IOMMU_ACCESS_WRITE.
> +
> + @param[in] This The protocol instance pointer.
> + @param[in] DeviceHandle The device who initiates the DMA access
> request.
> + @param[in] Mapping The mapping value returned from Map().
> + @param[in] IoMmuAccess The IOMMU access.
> +
> + @retval EFI_SUCCESS The IoMmuAccess is set for the memory
> range specified by DeviceAddress and Length.
> + @retval EFI_INVALID_PARAMETER DeviceHandle is an invalid handle.
> + @retval EFI_INVALID_PARAMETER Mapping is not a value that was returned
> by Map().
> + @retval EFI_INVALID_PARAMETER IoMmuAccess specified an illegal
> combination of access.
> + @retval EFI_UNSUPPORTED DeviceHandle is unknown by the
> IOMMU.
> + @retval EFI_UNSUPPORTED The bit mask of IoMmuAccess is not
> supported by the IOMMU.
> + @retval EFI_UNSUPPORTED The IOMMU does not support the
> memory range specified by Mapping.
> + @retval EFI_OUT_OF_RESOURCES There are not enough resources
> available to modify the IOMMU access.
> + @retval EFI_DEVICE_ERROR The IOMMU device reported an error
> while attempting the operation.
> +
> +**/
> +EFI_STATUS
> +EFIAPI
> +IoMmuSetAttribute (
> + IN EDKII_IOMMU_PROTOCOL *This,
> + IN EFI_HANDLE DeviceHandle,
> + IN VOID *Mapping,
> + IN UINT64 IoMmuAccess
> + )
> +{
> + return EFI_UNSUPPORTED;
> +}
> +
> +EDKII_IOMMU_PROTOCOL mAmdSev = {
> + EDKII_IOMMU_PROTOCOL_REVISION,
> + IoMmuSetAttribute,
> + IoMmuMap,
> + IoMmuUnmap,
> + IoMmuAllocateBuffer,
> + IoMmuFreeBuffer,
> +};
> +
> +/**
> + Initialize Iommu Protocol.
> +
> +**/
> +VOID
> +EFIAPI
> +AmdSevInstallIommuProtocol (
> + VOID
> + )
> +{
> + EFI_STATUS Status;
> + EFI_HANDLE Handle;
> +
> + Handle = NULL;
> + Status = gBS->InstallMultipleProtocolInterfaces (
> + &Handle,
> + &gEdkiiIoMmuProtocolGuid, &mAmdSev,
> + NULL
> + );
> + ASSERT_EFI_ERROR (Status);
> +}
> diff --git a/OvmfPkg/AmdSevDxe/AmdSevMmio.c
> b/OvmfPkg/AmdSevDxe/AmdSevMmio.c
> new file mode 100644
> index 000000000000..b623f82b7baa
> --- /dev/null
> +++ b/OvmfPkg/AmdSevDxe/AmdSevMmio.c
> @@ -0,0 +1,50 @@
> +/** @file
> +
> + Implements routines to clear C-bit from MMIO Memory Range
> +
> + 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 "AmdSevMmio.h"
> +
> +/**
> +
> + 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 NonExistent
> + memory space can gurantee that any MMIO mapped later will have C-bit
> cleared.
> +*/
> +VOID
> +EFIAPI
> +AmdSevClearEncMaskMmioRange (
> + VOID
> + )
> +{
> + EFI_STATUS Status;
> + EFI_GCD_MEMORY_SPACE_DESCRIPTOR *AllDescMap;
> + UINTN NumEntries;
> + UINTN Index;
> +
> + Status = gDS->GetMemorySpaceMap (&NumEntries, &AllDescMap);
> + if (Status == EFI_SUCCESS) {
> + 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);
> + }
> + }
> + }
> +}
> --
> 2.7.4
>
> _______________________________________________
> edk2-devel mailing list
> edk2-devel@lists.01.org
> https://lists.01.org/mailman/listinfo/edk2-devel
^ permalink raw reply [flat|nested] 42+ messages in thread
* Re: [RFC v4 06/13] OvmfPkg:AmdSevDxe: add AmdSevDxe driver
2017-05-10 22:09 ` [RFC v4 06/13] OvmfPkg:AmdSevDxe: add AmdSevDxe driver Brijesh Singh
2017-05-11 0:56 ` Yao, Jiewen
@ 2017-05-11 15:19 ` Laszlo Ersek
2017-05-11 15:53 ` Laszlo Ersek
2017-05-11 18:12 ` Brijesh Singh
1 sibling, 2 replies; 42+ messages in thread
From: Laszlo Ersek @ 2017-05-11 15:19 UTC (permalink / raw)
To: Brijesh Singh, edk2-devel
Cc: Thomas.Lendacky, Jordan Justen, Jiewen Yao, leo.duran
comments below:
On 05/11/17 00:09, Brijesh Singh wrote:
> When SEV is enabled, the MMIO memory range must be mapped as unencrypted
> (i.e C-bit cleared) and DMA must be performed on unencrypted memory.
>
> The patch adds a DXE driver that runs early in boot and clears the memory
> encryption attribute from MMIO/NonExistent memory ranges and installs a
> IOMMU protocol to provide the DMA support for PCIHostBridge and other drivers.
(1) Please mention that the C bit is cleared for MMIO GCD entries in
order to cover the ranges that were added during the PEI phase (through
memory resource descriptor HOBs).
Also mention that the NonExistent ranges are processed in order to
cover, in advance, MMIO ranges added later in the DXE phase by various
device drivers, via the appropriate DXE memory space services.
Finally, please mention that the approach is not transparent for later
addition of system memory ranges to the GCD memory space map. (Such
ranges should be encrypted.) OVMF does not do such a thing at the
moment, so this approach should be OK.
I think we should also credit Jiewen for both ideas, namely the IOMMU
stuff and the handling of NonExistent ranges (in anticipation of future
MMIO additions), so please add
Suggested-by: Jiewen Yao <jiewen.yao@intel.com>
>
> The driver produces IOMMU protocol introduce by Jiewen
> https://lists.01.org/pipermail/edk2-devel/2017-May/010462.html
>
>
> Cc: Jordan Justen <jordan.l.justen@intel.com>
> Cc: Laszlo Ersek <lersek@redhat.com>
> Cc: Leo Duran <leo.duran@amd.com>
> Cc: Jiewen Yao <jiewen.yao@intel.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
> ---
> OvmfPkg/OvmfPkgIa32X64.dsc | 1 +
> OvmfPkg/OvmfPkgX64.dsc | 1 +
> OvmfPkg/OvmfPkgIa32X64.fdf | 2 +
> OvmfPkg/OvmfPkgX64.fdf | 2 +
> OvmfPkg/AmdSevDxe/AmdSevDxe.inf | 49 +++
> OvmfPkg/AmdSevDxe/AmdSevIommu.h | 43 ++
> OvmfPkg/AmdSevDxe/AmdSevMmio.h | 41 ++
> OvmfPkg/AmdSevDxe/AmdSevDxe.c | 52 +++
> OvmfPkg/AmdSevDxe/AmdSevIommu.c | 459 ++++++++++++++++++++
> OvmfPkg/AmdSevDxe/AmdSevMmio.c | 50 +++
> 10 files changed, 700 insertions(+)
>
> diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
> index 9403f76ce862..ee6f98d68b73 100644
> --- a/OvmfPkg/OvmfPkgIa32X64.dsc
> +++ b/OvmfPkg/OvmfPkgIa32X64.dsc
> @@ -827,6 +827,7 @@ [Components.X64]
> !endif
>
> OvmfPkg/PlatformDxe/Platform.inf
> + OvmfPkg/AmdSevDxe/AmdSevDxe.inf
>
> !if $(SMM_REQUIRE) == TRUE
> OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
> diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
> index e137143f7afa..b5f26e06e60b 100644
> --- a/OvmfPkg/OvmfPkgX64.dsc
> +++ b/OvmfPkg/OvmfPkgX64.dsc
> @@ -825,6 +825,7 @@ [Components]
> !endif
>
> OvmfPkg/PlatformDxe/Platform.inf
> + OvmfPkg/AmdSevDxe/AmdSevDxe.inf
>
> !if $(SMM_REQUIRE) == TRUE
> OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
> diff --git a/OvmfPkg/OvmfPkgIa32X64.fdf b/OvmfPkg/OvmfPkgIa32X64.fdf
> index 5233314139bc..12871860d001 100644
> --- a/OvmfPkg/OvmfPkgIa32X64.fdf
> +++ b/OvmfPkg/OvmfPkgIa32X64.fdf
> @@ -190,6 +190,7 @@ [FV.DXEFV]
> APRIORI DXE {
> INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
> INF MdeModulePkg/Universal/PCD/Dxe/Pcd.inf
> + INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf
> !if $(SMM_REQUIRE) == FALSE
> INF OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
> !endif
> @@ -351,6 +352,7 @@ [FV.DXEFV]
> INF OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf
> INF OvmfPkg/VirtioGpuDxe/VirtioGpu.inf
> INF OvmfPkg/PlatformDxe/Platform.inf
> +INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf
>
> !if $(SMM_REQUIRE) == TRUE
> INF OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
> diff --git a/OvmfPkg/OvmfPkgX64.fdf b/OvmfPkg/OvmfPkgX64.fdf
> index 36150101e784..ae6e66a1c08d 100644
> --- a/OvmfPkg/OvmfPkgX64.fdf
> +++ b/OvmfPkg/OvmfPkgX64.fdf
> @@ -190,6 +190,7 @@ [FV.DXEFV]
> APRIORI DXE {
> INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
> INF MdeModulePkg/Universal/PCD/Dxe/Pcd.inf
> + INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf
> !if $(SMM_REQUIRE) == FALSE
> INF OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
> !endif
> @@ -351,6 +352,7 @@ [FV.DXEFV]
> INF OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf
> INF OvmfPkg/VirtioGpuDxe/VirtioGpu.inf
> INF OvmfPkg/PlatformDxe/Platform.inf
> +INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf
>
> !if $(SMM_REQUIRE) == TRUE
> INF OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
> diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.inf b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
> new file mode 100644
> index 000000000000..775dda9be386
> --- /dev/null
> +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
> @@ -0,0 +1,49 @@
> +#/** @file
> +#
> +# Driver clears the encryption attribute from MMIO regions and installs IOMMU
> +# protcol to provides DMA support for PciHostBridge and others
> +#
> +# 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.
> +#
> +#**/
> +
> +[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
> + AmdSevIommu.c
> + AmdSevMmio.c
> +
> +[Packages]
> + MdePkg/MdePkg.dec
> + MdeModulePkg/MdeModulePkg.dec
> + OvmfPkg/OvmfPkg.dec
> +
> +[LibraryClasses]
> + BaseLib
> + UefiLib
> + UefiDriverEntryPoint
> + UefiBootServicesTableLib
> + DxeServicesTableLib
> + DebugLib
> + MemEncryptSevLib
> +
> +[Protocols]
> + gEdkiiIoMmuProtocolGuid ## PRODUCES
> +
> +[Depex]
> + TRUE
> diff --git a/OvmfPkg/AmdSevDxe/AmdSevIommu.h b/OvmfPkg/AmdSevDxe/AmdSevIommu.h
> new file mode 100644
> index 000000000000..5712cb57052d
> --- /dev/null
> +++ b/OvmfPkg/AmdSevDxe/AmdSevIommu.h
> @@ -0,0 +1,43 @@
> +/** @file
> +
> + The protocol provides support to allocate, free, map and umap a DMA buffer for
> + bus master (e.g PciHostBridge). When SEV is enabled, the DMA operations must
> + be performed on unencrypted buffer hence protocol clear the encryption bit
> + from the DMA buffer.
> +
> + Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
> + 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.
> +
> +**/
> +
> +#ifndef __AMDSEVIOMMU_H_
> +#define __AMDSEVIOMMU_H
> +
> +#include <Protocol/IoMmu.h>
> +
> +#include <Library/BaseLib.h>
> +#include <Library/DebugLib.h>
> +#include <Library/BaseMemoryLib.h>
> +#include <Library/MemoryAllocationLib.h>
> +#include <Library/UefiBootServicesTableLib.h>
> +#include <Library/MemEncryptSevLib.h>
> +
> +/**
> + Install IOMMU protocol to provide the DMA support for PciHostBridge and
> + MemEncryptSevLib.
> +
> +**/
> +VOID
> +EFIAPI
> +AmdSevInstallIommuProtocol (
> + VOID
> + );
> +
> +#endif
> diff --git a/OvmfPkg/AmdSevDxe/AmdSevMmio.h b/OvmfPkg/AmdSevDxe/AmdSevMmio.h
> new file mode 100644
> index 000000000000..c6191025d921
> --- /dev/null
> +++ b/OvmfPkg/AmdSevDxe/AmdSevMmio.h
> @@ -0,0 +1,41 @@
> +/** @file
> +
> + Implements routines to clear C-bit from MMIO Memory Range
> +
> + 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.
> +
> +**/
> +
> +#ifndef __AMDSEVMMIO_H_
> +#define __AMDSEVMMIO_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>
> +
> +/**
> +
> + 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 NonExistent
> + memory space can gurantee that any MMIO mapped later will have C-bit cleared.
> +*/
> +VOID
> +EFIAPI
> +AmdSevClearEncMaskMmioRange (
> + VOID
> + );
> +
> +#endif
> diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.c b/OvmfPkg/AmdSevDxe/AmdSevDxe.c
> new file mode 100644
> index 000000000000..e22e7ef7314f
> --- /dev/null
> +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.c
> @@ -0,0 +1,52 @@
> +/** @file
> +
> + AMD Sev Dxe driver. The driver runs early in DXE phase and clears C-bit from
> + MMIO space and installs EDKII_IOMMU_PROTOCOL to provide the support for DMA
> + operations 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/MemEncryptSevLib.h>
> +
> +#include "AmdSevMmio.h"
> +#include "AmdSevIommu.h"
> +
> +EFI_STATUS
> +EFIAPI
> +AmdSevDxeEntryPoint (
> + IN EFI_HANDLE ImageHandle,
> + IN EFI_SYSTEM_TABLE *SystemTable
> + )
> +{
> + //
> + // Do nothing when SEV is not enabled
> + //
> + if (!MemEncryptSevIsEnabled ()) {
> + return EFI_SUCCESS;
> + }
(2) The status code should be EFI_UNSUPPORTED or EFI_ABORTED. Returning
with EFI_SUCCESS will uselessly keep the driver in memory.
> +
> + //
> + // Clear C-bit from MMIO Memory Range
> + //
> + AmdSevClearEncMaskMmioRange ();
> +
> + //
> + // Install IOMMU protocol to provide DMA support for PCIHostBridgeIo and
> + // AmdSevMemEncryptLib.
(3) What is AmdSevMemEncryptLib? Is this comment perhaps stale?
> + //
> + AmdSevInstallIommuProtocol ();
> +
> + return EFI_SUCCESS;
> +}
> diff --git a/OvmfPkg/AmdSevDxe/AmdSevIommu.c b/OvmfPkg/AmdSevDxe/AmdSevIommu.c
> new file mode 100644
> index 000000000000..9b35469ca34f
> --- /dev/null
> +++ b/OvmfPkg/AmdSevDxe/AmdSevIommu.c
> @@ -0,0 +1,459 @@
> +/** @file
> + AmdSevIommu related function
> +
> + The protocol provides support to allocate, free, map and umap a DMA buffer for
> + bus master (e.g PciHostBridge). When SEV is enabled, the DMA operations must
> + be performed on unencrypted buffer hence we use a bounce buffer to map the host
> + buffer into an unencrypted buffer.
> +
> + 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 "AmdSevIommu.h"
> +
> +typedef struct {
> + EDKII_IOMMU_OPERATION Operation;
> + UINTN NumberOfBytes;
> + UINTN NumberOfPages;
> + EFI_PHYSICAL_ADDRESS HostAddress;
> + EFI_PHYSICAL_ADDRESS DeviceAddress;
> +} MAP_INFO;
> +
> +#define NO_MAPPING (VOID *) (UINTN) -1
> +
> +/**
> + Provides the controller-specific addresses required to access system memory from a
> + DMA bus master. On SEV guest, the DMA operations must be performed on shared
> + buffer hence we allocate a bounce buffer to map the HostAddress to a DeviceAddress.
> + The Encryption attribute is removed from the DeviceAddress buffer.
> +
> + @param This The protocol instance pointer.
> + @param Operation Indicates if the bus master is going to read or
> + write to system memory.
> + @param HostAddress The system memory address to map to the PCI controller.
> + @param NumberOfBytes On input the number of bytes to map. On output
> + the number of bytes
> + that were mapped.
> + @param DeviceAddress The resulting map address for the bus master PCI
> + controller to use to
> + access the hosts HostAddress.
> + @param Mapping A resulting value to pass to Unmap().
> +
> + @retval EFI_SUCCESS The range was mapped for the returned NumberOfBytes.
> + @retval EFI_UNSUPPORTED The HostAddress cannot be mapped as a common buffer.
> + @retval EFI_INVALID_PARAMETER One or more parameters are invalid.
> + @retval EFI_OUT_OF_RESOURCES The request could not be completed due to a lack
> + of resources.
> + @retval EFI_DEVICE_ERROR The system hardware could not map the requested address.
> +
> +**/
> +EFI_STATUS
> +EFIAPI
> +IoMmuMap (
> + IN EDKII_IOMMU_PROTOCOL *This,
> + IN EDKII_IOMMU_OPERATION Operation,
> + IN VOID *HostAddress,
> + IN OUT UINTN *NumberOfBytes,
> + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress,
> + OUT VOID **Mapping
> + )
> +{
> + EFI_STATUS Status;
> + EFI_PHYSICAL_ADDRESS PhysicalAddress;
> + MAP_INFO *MapInfo;
> + EFI_PHYSICAL_ADDRESS DmaMemoryTop;
> + EFI_ALLOCATE_TYPE AllocateType;
> +
> + if (HostAddress == NULL || NumberOfBytes == NULL || DeviceAddress == NULL ||
> + Mapping == NULL) {
> + return EFI_INVALID_PARAMETER;
> + }
> +
> + //
> + // Make sure that Operation is valid
> + //
> + if ((UINT32) Operation >= EdkiiIoMmuOperationMaximum) {
> + return EFI_INVALID_PARAMETER;
> + }
> + PhysicalAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) HostAddress;
> +
> + DmaMemoryTop = (UINTN)-1;
> + AllocateType = AllocateAnyPages;
> +
> + if (((Operation != EdkiiIoMmuOperationBusMasterRead64 &&
> + Operation != EdkiiIoMmuOperationBusMasterWrite64 &&
> + Operation != EdkiiIoMmuOperationBusMasterCommonBuffer64)) &&
> + ((PhysicalAddress + *NumberOfBytes) > SIZE_4GB)) {
> + //
> + // If the root bridge or the device cannot handle performing DMA above
> + // 4GB but any part of the DMA transfer being mapped is above 4GB, then
> + // map the DMA transfer to a buffer below 4GB.
> + //
> + DmaMemoryTop = SIZE_4GB - 1;
> + AllocateType = AllocateMaxAddress;
> +
> + if (Operation == EdkiiIoMmuOperationBusMasterCommonBuffer ||
> + Operation == EdkiiIoMmuOperationBusMasterCommonBuffer64) {
> + //
> + // Common Buffer operations can not be remapped. If the common buffer
> + // if above 4GB, then it is not possible to generate a mapping, so return
> + // an error.
> + //
> + return EFI_UNSUPPORTED;
> + }
> + }
> +
> + //
> + // CommandBuffer was allocated by us (AllocateBuffer) and is already in
> + // unencryted buffer so no need to create bounce buffer
> + //
> + if (Operation == EdkiiIoMmuOperationBusMasterCommonBuffer ||
> + Operation == EdkiiIoMmuOperationBusMasterCommonBuffer64) {
> + *Mapping = NO_MAPPING;
> + *DeviceAddress = PhysicalAddress;
> +
> + return EFI_SUCCESS;
> + }
> +
> + //
> + // Allocate a MAP_INFO structure to remember the mapping when Unmap() is
> + // called later.
> + //
> + MapInfo = AllocatePool (sizeof (MAP_INFO));
> + if (MapInfo == NULL) {
> + *NumberOfBytes = 0;
> + return EFI_OUT_OF_RESOURCES;
> + }
> +
> + //
> + // Initialize the MAP_INFO structure
> + //
> + MapInfo->Operation = Operation;
> + MapInfo->NumberOfBytes = *NumberOfBytes;
> + MapInfo->NumberOfPages = EFI_SIZE_TO_PAGES (MapInfo->NumberOfBytes);
> + MapInfo->HostAddress = PhysicalAddress;
> + MapInfo->DeviceAddress = DmaMemoryTop;
> +
> + //
> + // Allocate a buffer to map the transfer to.
> + //
> + Status = gBS->AllocatePages (
> + AllocateType,
> + EfiBootServicesData,
> + MapInfo->NumberOfPages,
> + &MapInfo->DeviceAddress
> + );
> + if (EFI_ERROR (Status)) {
> + FreePool (MapInfo);
> + *NumberOfBytes = 0;
> + return Status;
> + }
> +
> + //
> + // Clear the memory encryption mask from the device buffer
> + //
> + Status = MemEncryptSevClearPageEncMask (0, MapInfo->DeviceAddress, MapInfo->NumberOfPages, TRUE);
> + ASSERT_EFI_ERROR(Status);
> +
> + //
> + // If this is a read operation from the Bus Master's point of view,
> + // then copy the contents of the real buffer into the mapped buffer
> + // so the Bus Master can read the contents of the real buffer.
> + //
> + if (Operation == EdkiiIoMmuOperationBusMasterRead ||
> + Operation == EdkiiIoMmuOperationBusMasterRead64) {
> + CopyMem (
> + (VOID *) (UINTN) MapInfo->DeviceAddress,
> + (VOID *) (UINTN) MapInfo->HostAddress,
> + MapInfo->NumberOfBytes
> + );
> + }
> +
> + //
> + // The DeviceAddress is the address of the maped buffer below 4GB
> + //
> + *DeviceAddress = MapInfo->DeviceAddress;
> +
> + //
> + // Return a pointer to the MAP_INFO structure in Mapping
> + //
> + *Mapping = MapInfo;
> +
> + DEBUG ((DEBUG_VERBOSE, "%a Host 0x%Lx Device 0x%Lx Pages 0x%Lx Bytes 0x%Lx\n",
> + __FUNCTION__, MapInfo->DeviceAddress, MapInfo->HostAddress,
> + MapInfo->NumberOfPages, MapInfo->NumberOfBytes));
> +
> + return EFI_SUCCESS;
> +}
> +
> +/**
> + Completes the Map() operation and releases any corresponding resources.
> +
> + @param This The protocol instance pointer.
> + @param Mapping The mapping value returned from Map().
> +
> + @retval EFI_SUCCESS The range was unmapped.
> + @retval EFI_INVALID_PARAMETER Mapping is not a value that was returned by Map().
> + @retval EFI_DEVICE_ERROR The data was not committed to the target system memory.
> +**/
> +EFI_STATUS
> +EFIAPI
> +IoMmuUnmap (
> + IN EDKII_IOMMU_PROTOCOL *This,
> + IN VOID *Mapping
> + )
> +{
> + MAP_INFO *MapInfo;
> + EFI_STATUS Status;
> +
> + if (Mapping == NULL) {
> + return EFI_INVALID_PARAMETER;
> + }
> +
> + //
> + // See if the Map() operation associated with this Unmap() required a mapping
> + // buffer. If a mapping buffer was not required, then this function simply
> + // buffer. If a mapping buffer was not required, then this function simply
> + //
> + if (Mapping == NO_MAPPING) {
> + return EFI_SUCCESS;
> + }
> +
> + MapInfo = (MAP_INFO *)Mapping;
> +
> + //
> + // If this is a write operation from the Bus Master's point of view,
> + // then copy the contents of the mapped buffer into the real buffer
> + // so the processor can read the contents of the real buffer.
> + //
> + if (MapInfo->Operation == EdkiiIoMmuOperationBusMasterWrite ||
> + MapInfo->Operation == EdkiiIoMmuOperationBusMasterWrite64) {
> + CopyMem (
> + (VOID *) (UINTN) MapInfo->HostAddress,
> + (VOID *) (UINTN) MapInfo->DeviceAddress,
> + MapInfo->NumberOfBytes
> + );
> + }
> +
> + DEBUG ((DEBUG_VERBOSE, "%a Host 0x%Lx Device 0x%Lx Pages 0x%Lx Bytes 0x%Lx\n",
> + __FUNCTION__, MapInfo->DeviceAddress, MapInfo->HostAddress,
> + MapInfo->NumberOfPages, MapInfo->NumberOfBytes));
> + //
> + // Restore the memory encryption mask
> + //
> + Status = MemEncryptSevSetPageEncMask (0, MapInfo->DeviceAddress, MapInfo->NumberOfPages, TRUE);
> + ASSERT_EFI_ERROR(Status);
> +
> + //
> + // Free the mapped buffer and the MAP_INFO structure.
> + //
> + gBS->FreePages (MapInfo->DeviceAddress, MapInfo->NumberOfPages);
> + FreePool (Mapping);
> + return EFI_SUCCESS;
> +}
> +
> +/**
> + Allocates pages that are suitable for an OperationBusMasterCommonBuffer or
> + OperationBusMasterCommonBuffer64 mapping.
> +
> + @param This The protocol instance pointer.
> + @param Type This parameter is not used and must be ignored.
> + @param MemoryType The type of memory to allocate, EfiBootServicesData
> + or EfiRuntimeServicesData.
> + @param Pages The number of pages to allocate.
> + @param HostAddress A pointer to store the base system memory address
> + of the allocated range.
> + @param Attributes The requested bit mask of attributes for the allocated range.
> +
> + @retval EFI_SUCCESS The requested memory pages were allocated.
> + @retval EFI_UNSUPPORTED Attributes is unsupported. The only legal attribute
> + bits are MEMORY_WRITE_COMBINE and MEMORY_CACHED.
> + @retval EFI_INVALID_PARAMETER One or more parameters are invalid.
> + @retval EFI_OUT_OF_RESOURCES The memory pages could not be allocated.
> +
> +**/
> +EFI_STATUS
> +EFIAPI
> +IoMmuAllocateBuffer (
> + IN EDKII_IOMMU_PROTOCOL *This,
> + IN EFI_ALLOCATE_TYPE Type,
> + IN EFI_MEMORY_TYPE MemoryType,
> + IN UINTN Pages,
> + IN OUT VOID **HostAddress,
> + IN UINT64 Attributes
> + )
> +{
> + EFI_STATUS Status;
> + EFI_PHYSICAL_ADDRESS PhysicalAddress;
> +
> + //
> + // Validate Attributes
> + //
> + if ((Attributes & EDKII_IOMMU_ATTRIBUTE_INVALID_FOR_ALLOCATE_BUFFER) != 0) {
> + return EFI_UNSUPPORTED;
> + }
> +
> + //
> + // Check for invalid inputs
> + //
> + if (HostAddress == NULL) {
> + return EFI_INVALID_PARAMETER;
> + }
> +
> + //
> + // The only valid memory types are EfiBootServicesData and
> + // EfiRuntimeServicesData
> + //
> + if (MemoryType != EfiBootServicesData &&
> + MemoryType != EfiRuntimeServicesData) {
> + return EFI_INVALID_PARAMETER;
> + }
> +
> + PhysicalAddress = (UINTN)-1;
> + if ((Attributes & EDKII_IOMMU_ATTRIBUTE_DUAL_ADDRESS_CYCLE) == 0) {
> + //
> + // Limit allocations to memory below 4GB
> + //
> + PhysicalAddress = SIZE_4GB - 1;
> + }
> + Status = gBS->AllocatePages (
> + AllocateMaxAddress,
> + MemoryType,
> + Pages,
> + &PhysicalAddress
> + );
> + if (!EFI_ERROR (Status)) {
> + *HostAddress = (VOID *) (UINTN) PhysicalAddress;
> +
> + //
> + // Clear memory encryption mask
> + //
> + Status = MemEncryptSevClearPageEncMask (0, PhysicalAddress, Pages, TRUE);
> + ASSERT_EFI_ERROR(Status);
> + }
> +
> + DEBUG ((DEBUG_VERBOSE, "%a Address 0x%Lx Pages 0x%Lx\n", __FUNCTION__, PhysicalAddress, Pages));
> + return Status;
> +}
> +
> +/**
> + Frees memory that was allocated with AllocateBuffer().
> +
> + @param This The protocol instance pointer.
> + @param Pages The number of pages to free.
> + @param HostAddress The base system memory address of the allocated range.
> +
> + @retval EFI_SUCCESS The requested memory pages were freed.
> + @retval EFI_INVALID_PARAMETER The memory range specified by HostAddress and Pages
> + was not allocated with AllocateBuffer().
> +
> +**/
> +EFI_STATUS
> +EFIAPI
> +IoMmuFreeBuffer (
> + IN EDKII_IOMMU_PROTOCOL *This,
> + IN UINTN Pages,
> + IN VOID *HostAddress
> + )
> +{
> + EFI_STATUS Status;
> +
> + //
> + // Set memory encryption mask
> + //
> + Status = MemEncryptSevSetPageEncMask (0, (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress, Pages, TRUE);
> + ASSERT_EFI_ERROR(Status);
> +
> + DEBUG ((DEBUG_VERBOSE, "%a Address 0x%Lx Pages 0x%Lx\n", __FUNCTION__, (UINTN)HostAddress, Pages));
> + return gBS->FreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) HostAddress, Pages);
> +}
> +
> +
> +/**
> + Set IOMMU attribute for a system memory.
> +
> + If the IOMMU protocol exists, the system memory cannot be used
> + for DMA by default.
> +
> + When a device requests a DMA access for a system memory,
> + the device driver need use SetAttribute() to update the IOMMU
> + attribute to request DMA access (read and/or write).
> +
> + The DeviceHandle is used to identify which device submits the request.
> + The IOMMU implementation need translate the device path to an IOMMU device ID,
> + and set IOMMU hardware register accordingly.
> + 1) DeviceHandle can be a standard PCI device.
> + The memory for BusMasterRead need set EDKII_IOMMU_ACCESS_READ.
> + The memory for BusMasterWrite need set EDKII_IOMMU_ACCESS_WRITE.
> + The memory for BusMasterCommonBuffer need set EDKII_IOMMU_ACCESS_READ|EDKII_IOMMU_ACCESS_WRITE.
> + After the memory is used, the memory need set 0 to keep it being protected.
> + 2) DeviceHandle can be an ACPI device (ISA, I2C, SPI, etc).
> + The memory for DMA access need set EDKII_IOMMU_ACCESS_READ and/or EDKII_IOMMU_ACCESS_WRITE.
> +
> + @param[in] This The protocol instance pointer.
> + @param[in] DeviceHandle The device who initiates the DMA access request.
> + @param[in] Mapping The mapping value returned from Map().
> + @param[in] IoMmuAccess The IOMMU access.
> +
> + @retval EFI_SUCCESS The IoMmuAccess is set for the memory range specified by DeviceAddress and Length.
> + @retval EFI_INVALID_PARAMETER DeviceHandle is an invalid handle.
> + @retval EFI_INVALID_PARAMETER Mapping is not a value that was returned by Map().
> + @retval EFI_INVALID_PARAMETER IoMmuAccess specified an illegal combination of access.
> + @retval EFI_UNSUPPORTED DeviceHandle is unknown by the IOMMU.
> + @retval EFI_UNSUPPORTED The bit mask of IoMmuAccess is not supported by the IOMMU.
> + @retval EFI_UNSUPPORTED The IOMMU does not support the memory range specified by Mapping.
> + @retval EFI_OUT_OF_RESOURCES There are not enough resources available to modify the IOMMU access.
> + @retval EFI_DEVICE_ERROR The IOMMU device reported an error while attempting the operation.
> +
> +**/
> +EFI_STATUS
> +EFIAPI
> +IoMmuSetAttribute (
> + IN EDKII_IOMMU_PROTOCOL *This,
> + IN EFI_HANDLE DeviceHandle,
> + IN VOID *Mapping,
> + IN UINT64 IoMmuAccess
> + )
> +{
> + return EFI_UNSUPPORTED;
> +}
> +
> +EDKII_IOMMU_PROTOCOL mAmdSev = {
> + EDKII_IOMMU_PROTOCOL_REVISION,
> + IoMmuSetAttribute,
> + IoMmuMap,
> + IoMmuUnmap,
> + IoMmuAllocateBuffer,
> + IoMmuFreeBuffer,
> +};
> +
> +/**
> + Initialize Iommu Protocol.
> +
> +**/
> +VOID
> +EFIAPI
> +AmdSevInstallIommuProtocol (
> + VOID
> + )
> +{
> + EFI_STATUS Status;
> + EFI_HANDLE Handle;
> +
> + Handle = NULL;
> + Status = gBS->InstallMultipleProtocolInterfaces (
> + &Handle,
> + &gEdkiiIoMmuProtocolGuid, &mAmdSev,
> + NULL
> + );
> + ASSERT_EFI_ERROR (Status);
> +}
> diff --git a/OvmfPkg/AmdSevDxe/AmdSevMmio.c b/OvmfPkg/AmdSevDxe/AmdSevMmio.c
> new file mode 100644
> index 000000000000..b623f82b7baa
> --- /dev/null
> +++ b/OvmfPkg/AmdSevDxe/AmdSevMmio.c
> @@ -0,0 +1,50 @@
> +/** @file
> +
> + Implements routines to clear C-bit from MMIO Memory Range
> +
> + 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 "AmdSevMmio.h"
> +
> +/**
> +
> + 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 NonExistent
> + memory space can gurantee that any MMIO mapped later will have C-bit cleared.
> +*/
> +VOID
> +EFIAPI
> +AmdSevClearEncMaskMmioRange (
> + VOID
> + )
> +{
> + EFI_STATUS Status;
> + EFI_GCD_MEMORY_SPACE_DESCRIPTOR *AllDescMap;
> + UINTN NumEntries;
> + UINTN Index;
> +
> + Status = gDS->GetMemorySpaceMap (&NumEntries, &AllDescMap);
> + if (Status == EFI_SUCCESS) {
> + 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);
> + }
> + }
(4) Right here I think you have a memory leak; gDS->GetMemorySpaceMap()
allocates AllDescMap dynamically (on success). Please free it with
FreePool().
Regarding the IOMMU protocol implementation, I'm going to rely on
Jiewen's review -- thank you Jiewen very much for that!
With the above fixed:
Reviewed-by: Laszlo Ersek <lersek@redhat.com>
Thanks,
Laszlo
> + }
> +}
>
^ permalink raw reply [flat|nested] 42+ messages in thread
* Re: [RFC v4 06/13] OvmfPkg:AmdSevDxe: add AmdSevDxe driver
2017-05-11 15:19 ` Laszlo Ersek
@ 2017-05-11 15:53 ` Laszlo Ersek
2017-05-11 17:43 ` Jordan Justen
2017-05-11 18:12 ` Brijesh Singh
1 sibling, 1 reply; 42+ messages in thread
From: Laszlo Ersek @ 2017-05-11 15:53 UTC (permalink / raw)
To: Brijesh Singh, edk2-devel
Cc: Thomas.Lendacky, Jordan Justen, Jiewen Yao, leo.duran
On 05/11/17 17:19, Laszlo Ersek wrote:
> comments below:
>
> On 05/11/17 00:09, Brijesh Singh wrote:
>> When SEV is enabled, the MMIO memory range must be mapped as unencrypted
>> (i.e C-bit cleared) and DMA must be performed on unencrypted memory.
>>
>> The patch adds a DXE driver that runs early in boot and clears the memory
>> encryption attribute from MMIO/NonExistent memory ranges and installs a
>> IOMMU protocol to provide the DMA support for PCIHostBridge and other drivers.
>
> (1) Please mention that the C bit is cleared for MMIO GCD entries in
> order to cover the ranges that were added during the PEI phase (through
> memory resource descriptor HOBs).
>
> Also mention that the NonExistent ranges are processed in order to
> cover, in advance, MMIO ranges added later in the DXE phase by various
> device drivers, via the appropriate DXE memory space services.
>
> Finally, please mention that the approach is not transparent for later
> addition of system memory ranges to the GCD memory space map. (Such
> ranges should be encrypted.) OVMF does not do such a thing at the
> moment, so this approach should be OK.
>
> I think we should also credit Jiewen for both ideas, namely the IOMMU
> stuff and the handling of NonExistent ranges (in anticipation of future
> MMIO additions), so please add
>
> Suggested-by: Jiewen Yao <jiewen.yao@intel.com>
(5) Please mention that the driver is being added to the APRIORI DXE
file for a separate reason as well (not just for the early clearing of
the C bit on MMIO/NonExistent): OvmfPkg's DXE phase modules that tailor
their behavior to SEV presence will assume that the IOMMU protocol
exported by this driver is available *at once*.
(If you fix this up as well, you can add my R-b -- see under (4).)
Thanks,
Laszlo
>
>>
>> The driver produces IOMMU protocol introduce by Jiewen
>> https://lists.01.org/pipermail/edk2-devel/2017-May/010462.html
>>
>>
>> Cc: Jordan Justen <jordan.l.justen@intel.com>
>> Cc: Laszlo Ersek <lersek@redhat.com>
>> Cc: Leo Duran <leo.duran@amd.com>
>> Cc: Jiewen Yao <jiewen.yao@intel.com>
>> Contributed-under: TianoCore Contribution Agreement 1.0
>> Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
>> ---
>> OvmfPkg/OvmfPkgIa32X64.dsc | 1 +
>> OvmfPkg/OvmfPkgX64.dsc | 1 +
>> OvmfPkg/OvmfPkgIa32X64.fdf | 2 +
>> OvmfPkg/OvmfPkgX64.fdf | 2 +
>> OvmfPkg/AmdSevDxe/AmdSevDxe.inf | 49 +++
>> OvmfPkg/AmdSevDxe/AmdSevIommu.h | 43 ++
>> OvmfPkg/AmdSevDxe/AmdSevMmio.h | 41 ++
>> OvmfPkg/AmdSevDxe/AmdSevDxe.c | 52 +++
>> OvmfPkg/AmdSevDxe/AmdSevIommu.c | 459 ++++++++++++++++++++
>> OvmfPkg/AmdSevDxe/AmdSevMmio.c | 50 +++
>> 10 files changed, 700 insertions(+)
>>
>> diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
>> index 9403f76ce862..ee6f98d68b73 100644
>> --- a/OvmfPkg/OvmfPkgIa32X64.dsc
>> +++ b/OvmfPkg/OvmfPkgIa32X64.dsc
>> @@ -827,6 +827,7 @@ [Components.X64]
>> !endif
>>
>> OvmfPkg/PlatformDxe/Platform.inf
>> + OvmfPkg/AmdSevDxe/AmdSevDxe.inf
>>
>> !if $(SMM_REQUIRE) == TRUE
>> OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
>> diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
>> index e137143f7afa..b5f26e06e60b 100644
>> --- a/OvmfPkg/OvmfPkgX64.dsc
>> +++ b/OvmfPkg/OvmfPkgX64.dsc
>> @@ -825,6 +825,7 @@ [Components]
>> !endif
>>
>> OvmfPkg/PlatformDxe/Platform.inf
>> + OvmfPkg/AmdSevDxe/AmdSevDxe.inf
>>
>> !if $(SMM_REQUIRE) == TRUE
>> OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
>> diff --git a/OvmfPkg/OvmfPkgIa32X64.fdf b/OvmfPkg/OvmfPkgIa32X64.fdf
>> index 5233314139bc..12871860d001 100644
>> --- a/OvmfPkg/OvmfPkgIa32X64.fdf
>> +++ b/OvmfPkg/OvmfPkgIa32X64.fdf
>> @@ -190,6 +190,7 @@ [FV.DXEFV]
>> APRIORI DXE {
>> INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
>> INF MdeModulePkg/Universal/PCD/Dxe/Pcd.inf
>> + INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf
>> !if $(SMM_REQUIRE) == FALSE
>> INF OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
>> !endif
>> @@ -351,6 +352,7 @@ [FV.DXEFV]
>> INF OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf
>> INF OvmfPkg/VirtioGpuDxe/VirtioGpu.inf
>> INF OvmfPkg/PlatformDxe/Platform.inf
>> +INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf
>>
>> !if $(SMM_REQUIRE) == TRUE
>> INF OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
>> diff --git a/OvmfPkg/OvmfPkgX64.fdf b/OvmfPkg/OvmfPkgX64.fdf
>> index 36150101e784..ae6e66a1c08d 100644
>> --- a/OvmfPkg/OvmfPkgX64.fdf
>> +++ b/OvmfPkg/OvmfPkgX64.fdf
>> @@ -190,6 +190,7 @@ [FV.DXEFV]
>> APRIORI DXE {
>> INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
>> INF MdeModulePkg/Universal/PCD/Dxe/Pcd.inf
>> + INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf
>> !if $(SMM_REQUIRE) == FALSE
>> INF OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
>> !endif
>> @@ -351,6 +352,7 @@ [FV.DXEFV]
>> INF OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf
>> INF OvmfPkg/VirtioGpuDxe/VirtioGpu.inf
>> INF OvmfPkg/PlatformDxe/Platform.inf
>> +INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf
>>
>> !if $(SMM_REQUIRE) == TRUE
>> INF OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
>> diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.inf b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
>> new file mode 100644
>> index 000000000000..775dda9be386
>> --- /dev/null
>> +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf
>> @@ -0,0 +1,49 @@
>> +#/** @file
>> +#
>> +# Driver clears the encryption attribute from MMIO regions and installs IOMMU
>> +# protcol to provides DMA support for PciHostBridge and others
>> +#
>> +# 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.
>> +#
>> +#**/
>> +
>> +[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
>> + AmdSevIommu.c
>> + AmdSevMmio.c
>> +
>> +[Packages]
>> + MdePkg/MdePkg.dec
>> + MdeModulePkg/MdeModulePkg.dec
>> + OvmfPkg/OvmfPkg.dec
>> +
>> +[LibraryClasses]
>> + BaseLib
>> + UefiLib
>> + UefiDriverEntryPoint
>> + UefiBootServicesTableLib
>> + DxeServicesTableLib
>> + DebugLib
>> + MemEncryptSevLib
>> +
>> +[Protocols]
>> + gEdkiiIoMmuProtocolGuid ## PRODUCES
>> +
>> +[Depex]
>> + TRUE
>> diff --git a/OvmfPkg/AmdSevDxe/AmdSevIommu.h b/OvmfPkg/AmdSevDxe/AmdSevIommu.h
>> new file mode 100644
>> index 000000000000..5712cb57052d
>> --- /dev/null
>> +++ b/OvmfPkg/AmdSevDxe/AmdSevIommu.h
>> @@ -0,0 +1,43 @@
>> +/** @file
>> +
>> + The protocol provides support to allocate, free, map and umap a DMA buffer for
>> + bus master (e.g PciHostBridge). When SEV is enabled, the DMA operations must
>> + be performed on unencrypted buffer hence protocol clear the encryption bit
>> + from the DMA buffer.
>> +
>> + Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
>> + 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.
>> +
>> +**/
>> +
>> +#ifndef __AMDSEVIOMMU_H_
>> +#define __AMDSEVIOMMU_H
>> +
>> +#include <Protocol/IoMmu.h>
>> +
>> +#include <Library/BaseLib.h>
>> +#include <Library/DebugLib.h>
>> +#include <Library/BaseMemoryLib.h>
>> +#include <Library/MemoryAllocationLib.h>
>> +#include <Library/UefiBootServicesTableLib.h>
>> +#include <Library/MemEncryptSevLib.h>
>> +
>> +/**
>> + Install IOMMU protocol to provide the DMA support for PciHostBridge and
>> + MemEncryptSevLib.
>> +
>> +**/
>> +VOID
>> +EFIAPI
>> +AmdSevInstallIommuProtocol (
>> + VOID
>> + );
>> +
>> +#endif
>> diff --git a/OvmfPkg/AmdSevDxe/AmdSevMmio.h b/OvmfPkg/AmdSevDxe/AmdSevMmio.h
>> new file mode 100644
>> index 000000000000..c6191025d921
>> --- /dev/null
>> +++ b/OvmfPkg/AmdSevDxe/AmdSevMmio.h
>> @@ -0,0 +1,41 @@
>> +/** @file
>> +
>> + Implements routines to clear C-bit from MMIO Memory Range
>> +
>> + 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.
>> +
>> +**/
>> +
>> +#ifndef __AMDSEVMMIO_H_
>> +#define __AMDSEVMMIO_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>
>> +
>> +/**
>> +
>> + 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 NonExistent
>> + memory space can gurantee that any MMIO mapped later will have C-bit cleared.
>> +*/
>> +VOID
>> +EFIAPI
>> +AmdSevClearEncMaskMmioRange (
>> + VOID
>> + );
>> +
>> +#endif
>> diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.c b/OvmfPkg/AmdSevDxe/AmdSevDxe.c
>> new file mode 100644
>> index 000000000000..e22e7ef7314f
>> --- /dev/null
>> +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.c
>> @@ -0,0 +1,52 @@
>> +/** @file
>> +
>> + AMD Sev Dxe driver. The driver runs early in DXE phase and clears C-bit from
>> + MMIO space and installs EDKII_IOMMU_PROTOCOL to provide the support for DMA
>> + operations 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/MemEncryptSevLib.h>
>> +
>> +#include "AmdSevMmio.h"
>> +#include "AmdSevIommu.h"
>> +
>> +EFI_STATUS
>> +EFIAPI
>> +AmdSevDxeEntryPoint (
>> + IN EFI_HANDLE ImageHandle,
>> + IN EFI_SYSTEM_TABLE *SystemTable
>> + )
>> +{
>> + //
>> + // Do nothing when SEV is not enabled
>> + //
>> + if (!MemEncryptSevIsEnabled ()) {
>> + return EFI_SUCCESS;
>> + }
>
> (2) The status code should be EFI_UNSUPPORTED or EFI_ABORTED. Returning
> with EFI_SUCCESS will uselessly keep the driver in memory.
>
>> +
>> + //
>> + // Clear C-bit from MMIO Memory Range
>> + //
>> + AmdSevClearEncMaskMmioRange ();
>> +
>> + //
>> + // Install IOMMU protocol to provide DMA support for PCIHostBridgeIo and
>> + // AmdSevMemEncryptLib.
>
> (3) What is AmdSevMemEncryptLib? Is this comment perhaps stale?
>
>> + //
>> + AmdSevInstallIommuProtocol ();
>> +
>> + return EFI_SUCCESS;
>> +}
>> diff --git a/OvmfPkg/AmdSevDxe/AmdSevIommu.c b/OvmfPkg/AmdSevDxe/AmdSevIommu.c
>> new file mode 100644
>> index 000000000000..9b35469ca34f
>> --- /dev/null
>> +++ b/OvmfPkg/AmdSevDxe/AmdSevIommu.c
>> @@ -0,0 +1,459 @@
>> +/** @file
>> + AmdSevIommu related function
>> +
>> + The protocol provides support to allocate, free, map and umap a DMA buffer for
>> + bus master (e.g PciHostBridge). When SEV is enabled, the DMA operations must
>> + be performed on unencrypted buffer hence we use a bounce buffer to map the host
>> + buffer into an unencrypted buffer.
>> +
>> + 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 "AmdSevIommu.h"
>> +
>> +typedef struct {
>> + EDKII_IOMMU_OPERATION Operation;
>> + UINTN NumberOfBytes;
>> + UINTN NumberOfPages;
>> + EFI_PHYSICAL_ADDRESS HostAddress;
>> + EFI_PHYSICAL_ADDRESS DeviceAddress;
>> +} MAP_INFO;
>> +
>> +#define NO_MAPPING (VOID *) (UINTN) -1
>> +
>> +/**
>> + Provides the controller-specific addresses required to access system memory from a
>> + DMA bus master. On SEV guest, the DMA operations must be performed on shared
>> + buffer hence we allocate a bounce buffer to map the HostAddress to a DeviceAddress.
>> + The Encryption attribute is removed from the DeviceAddress buffer.
>> +
>> + @param This The protocol instance pointer.
>> + @param Operation Indicates if the bus master is going to read or
>> + write to system memory.
>> + @param HostAddress The system memory address to map to the PCI controller.
>> + @param NumberOfBytes On input the number of bytes to map. On output
>> + the number of bytes
>> + that were mapped.
>> + @param DeviceAddress The resulting map address for the bus master PCI
>> + controller to use to
>> + access the hosts HostAddress.
>> + @param Mapping A resulting value to pass to Unmap().
>> +
>> + @retval EFI_SUCCESS The range was mapped for the returned NumberOfBytes.
>> + @retval EFI_UNSUPPORTED The HostAddress cannot be mapped as a common buffer.
>> + @retval EFI_INVALID_PARAMETER One or more parameters are invalid.
>> + @retval EFI_OUT_OF_RESOURCES The request could not be completed due to a lack
>> + of resources.
>> + @retval EFI_DEVICE_ERROR The system hardware could not map the requested address.
>> +
>> +**/
>> +EFI_STATUS
>> +EFIAPI
>> +IoMmuMap (
>> + IN EDKII_IOMMU_PROTOCOL *This,
>> + IN EDKII_IOMMU_OPERATION Operation,
>> + IN VOID *HostAddress,
>> + IN OUT UINTN *NumberOfBytes,
>> + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress,
>> + OUT VOID **Mapping
>> + )
>> +{
>> + EFI_STATUS Status;
>> + EFI_PHYSICAL_ADDRESS PhysicalAddress;
>> + MAP_INFO *MapInfo;
>> + EFI_PHYSICAL_ADDRESS DmaMemoryTop;
>> + EFI_ALLOCATE_TYPE AllocateType;
>> +
>> + if (HostAddress == NULL || NumberOfBytes == NULL || DeviceAddress == NULL ||
>> + Mapping == NULL) {
>> + return EFI_INVALID_PARAMETER;
>> + }
>> +
>> + //
>> + // Make sure that Operation is valid
>> + //
>> + if ((UINT32) Operation >= EdkiiIoMmuOperationMaximum) {
>> + return EFI_INVALID_PARAMETER;
>> + }
>> + PhysicalAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) HostAddress;
>> +
>> + DmaMemoryTop = (UINTN)-1;
>> + AllocateType = AllocateAnyPages;
>> +
>> + if (((Operation != EdkiiIoMmuOperationBusMasterRead64 &&
>> + Operation != EdkiiIoMmuOperationBusMasterWrite64 &&
>> + Operation != EdkiiIoMmuOperationBusMasterCommonBuffer64)) &&
>> + ((PhysicalAddress + *NumberOfBytes) > SIZE_4GB)) {
>> + //
>> + // If the root bridge or the device cannot handle performing DMA above
>> + // 4GB but any part of the DMA transfer being mapped is above 4GB, then
>> + // map the DMA transfer to a buffer below 4GB.
>> + //
>> + DmaMemoryTop = SIZE_4GB - 1;
>> + AllocateType = AllocateMaxAddress;
>> +
>> + if (Operation == EdkiiIoMmuOperationBusMasterCommonBuffer ||
>> + Operation == EdkiiIoMmuOperationBusMasterCommonBuffer64) {
>> + //
>> + // Common Buffer operations can not be remapped. If the common buffer
>> + // if above 4GB, then it is not possible to generate a mapping, so return
>> + // an error.
>> + //
>> + return EFI_UNSUPPORTED;
>> + }
>> + }
>> +
>> + //
>> + // CommandBuffer was allocated by us (AllocateBuffer) and is already in
>> + // unencryted buffer so no need to create bounce buffer
>> + //
>> + if (Operation == EdkiiIoMmuOperationBusMasterCommonBuffer ||
>> + Operation == EdkiiIoMmuOperationBusMasterCommonBuffer64) {
>> + *Mapping = NO_MAPPING;
>> + *DeviceAddress = PhysicalAddress;
>> +
>> + return EFI_SUCCESS;
>> + }
>> +
>> + //
>> + // Allocate a MAP_INFO structure to remember the mapping when Unmap() is
>> + // called later.
>> + //
>> + MapInfo = AllocatePool (sizeof (MAP_INFO));
>> + if (MapInfo == NULL) {
>> + *NumberOfBytes = 0;
>> + return EFI_OUT_OF_RESOURCES;
>> + }
>> +
>> + //
>> + // Initialize the MAP_INFO structure
>> + //
>> + MapInfo->Operation = Operation;
>> + MapInfo->NumberOfBytes = *NumberOfBytes;
>> + MapInfo->NumberOfPages = EFI_SIZE_TO_PAGES (MapInfo->NumberOfBytes);
>> + MapInfo->HostAddress = PhysicalAddress;
>> + MapInfo->DeviceAddress = DmaMemoryTop;
>> +
>> + //
>> + // Allocate a buffer to map the transfer to.
>> + //
>> + Status = gBS->AllocatePages (
>> + AllocateType,
>> + EfiBootServicesData,
>> + MapInfo->NumberOfPages,
>> + &MapInfo->DeviceAddress
>> + );
>> + if (EFI_ERROR (Status)) {
>> + FreePool (MapInfo);
>> + *NumberOfBytes = 0;
>> + return Status;
>> + }
>> +
>> + //
>> + // Clear the memory encryption mask from the device buffer
>> + //
>> + Status = MemEncryptSevClearPageEncMask (0, MapInfo->DeviceAddress, MapInfo->NumberOfPages, TRUE);
>> + ASSERT_EFI_ERROR(Status);
>> +
>> + //
>> + // If this is a read operation from the Bus Master's point of view,
>> + // then copy the contents of the real buffer into the mapped buffer
>> + // so the Bus Master can read the contents of the real buffer.
>> + //
>> + if (Operation == EdkiiIoMmuOperationBusMasterRead ||
>> + Operation == EdkiiIoMmuOperationBusMasterRead64) {
>> + CopyMem (
>> + (VOID *) (UINTN) MapInfo->DeviceAddress,
>> + (VOID *) (UINTN) MapInfo->HostAddress,
>> + MapInfo->NumberOfBytes
>> + );
>> + }
>> +
>> + //
>> + // The DeviceAddress is the address of the maped buffer below 4GB
>> + //
>> + *DeviceAddress = MapInfo->DeviceAddress;
>> +
>> + //
>> + // Return a pointer to the MAP_INFO structure in Mapping
>> + //
>> + *Mapping = MapInfo;
>> +
>> + DEBUG ((DEBUG_VERBOSE, "%a Host 0x%Lx Device 0x%Lx Pages 0x%Lx Bytes 0x%Lx\n",
>> + __FUNCTION__, MapInfo->DeviceAddress, MapInfo->HostAddress,
>> + MapInfo->NumberOfPages, MapInfo->NumberOfBytes));
>> +
>> + return EFI_SUCCESS;
>> +}
>> +
>> +/**
>> + Completes the Map() operation and releases any corresponding resources.
>> +
>> + @param This The protocol instance pointer.
>> + @param Mapping The mapping value returned from Map().
>> +
>> + @retval EFI_SUCCESS The range was unmapped.
>> + @retval EFI_INVALID_PARAMETER Mapping is not a value that was returned by Map().
>> + @retval EFI_DEVICE_ERROR The data was not committed to the target system memory.
>> +**/
>> +EFI_STATUS
>> +EFIAPI
>> +IoMmuUnmap (
>> + IN EDKII_IOMMU_PROTOCOL *This,
>> + IN VOID *Mapping
>> + )
>> +{
>> + MAP_INFO *MapInfo;
>> + EFI_STATUS Status;
>> +
>> + if (Mapping == NULL) {
>> + return EFI_INVALID_PARAMETER;
>> + }
>> +
>> + //
>> + // See if the Map() operation associated with this Unmap() required a mapping
>> + // buffer. If a mapping buffer was not required, then this function simply
>> + // buffer. If a mapping buffer was not required, then this function simply
>> + //
>> + if (Mapping == NO_MAPPING) {
>> + return EFI_SUCCESS;
>> + }
>> +
>> + MapInfo = (MAP_INFO *)Mapping;
>> +
>> + //
>> + // If this is a write operation from the Bus Master's point of view,
>> + // then copy the contents of the mapped buffer into the real buffer
>> + // so the processor can read the contents of the real buffer.
>> + //
>> + if (MapInfo->Operation == EdkiiIoMmuOperationBusMasterWrite ||
>> + MapInfo->Operation == EdkiiIoMmuOperationBusMasterWrite64) {
>> + CopyMem (
>> + (VOID *) (UINTN) MapInfo->HostAddress,
>> + (VOID *) (UINTN) MapInfo->DeviceAddress,
>> + MapInfo->NumberOfBytes
>> + );
>> + }
>> +
>> + DEBUG ((DEBUG_VERBOSE, "%a Host 0x%Lx Device 0x%Lx Pages 0x%Lx Bytes 0x%Lx\n",
>> + __FUNCTION__, MapInfo->DeviceAddress, MapInfo->HostAddress,
>> + MapInfo->NumberOfPages, MapInfo->NumberOfBytes));
>> + //
>> + // Restore the memory encryption mask
>> + //
>> + Status = MemEncryptSevSetPageEncMask (0, MapInfo->DeviceAddress, MapInfo->NumberOfPages, TRUE);
>> + ASSERT_EFI_ERROR(Status);
>> +
>> + //
>> + // Free the mapped buffer and the MAP_INFO structure.
>> + //
>> + gBS->FreePages (MapInfo->DeviceAddress, MapInfo->NumberOfPages);
>> + FreePool (Mapping);
>> + return EFI_SUCCESS;
>> +}
>> +
>> +/**
>> + Allocates pages that are suitable for an OperationBusMasterCommonBuffer or
>> + OperationBusMasterCommonBuffer64 mapping.
>> +
>> + @param This The protocol instance pointer.
>> + @param Type This parameter is not used and must be ignored.
>> + @param MemoryType The type of memory to allocate, EfiBootServicesData
>> + or EfiRuntimeServicesData.
>> + @param Pages The number of pages to allocate.
>> + @param HostAddress A pointer to store the base system memory address
>> + of the allocated range.
>> + @param Attributes The requested bit mask of attributes for the allocated range.
>> +
>> + @retval EFI_SUCCESS The requested memory pages were allocated.
>> + @retval EFI_UNSUPPORTED Attributes is unsupported. The only legal attribute
>> + bits are MEMORY_WRITE_COMBINE and MEMORY_CACHED.
>> + @retval EFI_INVALID_PARAMETER One or more parameters are invalid.
>> + @retval EFI_OUT_OF_RESOURCES The memory pages could not be allocated.
>> +
>> +**/
>> +EFI_STATUS
>> +EFIAPI
>> +IoMmuAllocateBuffer (
>> + IN EDKII_IOMMU_PROTOCOL *This,
>> + IN EFI_ALLOCATE_TYPE Type,
>> + IN EFI_MEMORY_TYPE MemoryType,
>> + IN UINTN Pages,
>> + IN OUT VOID **HostAddress,
>> + IN UINT64 Attributes
>> + )
>> +{
>> + EFI_STATUS Status;
>> + EFI_PHYSICAL_ADDRESS PhysicalAddress;
>> +
>> + //
>> + // Validate Attributes
>> + //
>> + if ((Attributes & EDKII_IOMMU_ATTRIBUTE_INVALID_FOR_ALLOCATE_BUFFER) != 0) {
>> + return EFI_UNSUPPORTED;
>> + }
>> +
>> + //
>> + // Check for invalid inputs
>> + //
>> + if (HostAddress == NULL) {
>> + return EFI_INVALID_PARAMETER;
>> + }
>> +
>> + //
>> + // The only valid memory types are EfiBootServicesData and
>> + // EfiRuntimeServicesData
>> + //
>> + if (MemoryType != EfiBootServicesData &&
>> + MemoryType != EfiRuntimeServicesData) {
>> + return EFI_INVALID_PARAMETER;
>> + }
>> +
>> + PhysicalAddress = (UINTN)-1;
>> + if ((Attributes & EDKII_IOMMU_ATTRIBUTE_DUAL_ADDRESS_CYCLE) == 0) {
>> + //
>> + // Limit allocations to memory below 4GB
>> + //
>> + PhysicalAddress = SIZE_4GB - 1;
>> + }
>> + Status = gBS->AllocatePages (
>> + AllocateMaxAddress,
>> + MemoryType,
>> + Pages,
>> + &PhysicalAddress
>> + );
>> + if (!EFI_ERROR (Status)) {
>> + *HostAddress = (VOID *) (UINTN) PhysicalAddress;
>> +
>> + //
>> + // Clear memory encryption mask
>> + //
>> + Status = MemEncryptSevClearPageEncMask (0, PhysicalAddress, Pages, TRUE);
>> + ASSERT_EFI_ERROR(Status);
>> + }
>> +
>> + DEBUG ((DEBUG_VERBOSE, "%a Address 0x%Lx Pages 0x%Lx\n", __FUNCTION__, PhysicalAddress, Pages));
>> + return Status;
>> +}
>> +
>> +/**
>> + Frees memory that was allocated with AllocateBuffer().
>> +
>> + @param This The protocol instance pointer.
>> + @param Pages The number of pages to free.
>> + @param HostAddress The base system memory address of the allocated range.
>> +
>> + @retval EFI_SUCCESS The requested memory pages were freed.
>> + @retval EFI_INVALID_PARAMETER The memory range specified by HostAddress and Pages
>> + was not allocated with AllocateBuffer().
>> +
>> +**/
>> +EFI_STATUS
>> +EFIAPI
>> +IoMmuFreeBuffer (
>> + IN EDKII_IOMMU_PROTOCOL *This,
>> + IN UINTN Pages,
>> + IN VOID *HostAddress
>> + )
>> +{
>> + EFI_STATUS Status;
>> +
>> + //
>> + // Set memory encryption mask
>> + //
>> + Status = MemEncryptSevSetPageEncMask (0, (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress, Pages, TRUE);
>> + ASSERT_EFI_ERROR(Status);
>> +
>> + DEBUG ((DEBUG_VERBOSE, "%a Address 0x%Lx Pages 0x%Lx\n", __FUNCTION__, (UINTN)HostAddress, Pages));
>> + return gBS->FreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) HostAddress, Pages);
>> +}
>> +
>> +
>> +/**
>> + Set IOMMU attribute for a system memory.
>> +
>> + If the IOMMU protocol exists, the system memory cannot be used
>> + for DMA by default.
>> +
>> + When a device requests a DMA access for a system memory,
>> + the device driver need use SetAttribute() to update the IOMMU
>> + attribute to request DMA access (read and/or write).
>> +
>> + The DeviceHandle is used to identify which device submits the request.
>> + The IOMMU implementation need translate the device path to an IOMMU device ID,
>> + and set IOMMU hardware register accordingly.
>> + 1) DeviceHandle can be a standard PCI device.
>> + The memory for BusMasterRead need set EDKII_IOMMU_ACCESS_READ.
>> + The memory for BusMasterWrite need set EDKII_IOMMU_ACCESS_WRITE.
>> + The memory for BusMasterCommonBuffer need set EDKII_IOMMU_ACCESS_READ|EDKII_IOMMU_ACCESS_WRITE.
>> + After the memory is used, the memory need set 0 to keep it being protected.
>> + 2) DeviceHandle can be an ACPI device (ISA, I2C, SPI, etc).
>> + The memory for DMA access need set EDKII_IOMMU_ACCESS_READ and/or EDKII_IOMMU_ACCESS_WRITE.
>> +
>> + @param[in] This The protocol instance pointer.
>> + @param[in] DeviceHandle The device who initiates the DMA access request.
>> + @param[in] Mapping The mapping value returned from Map().
>> + @param[in] IoMmuAccess The IOMMU access.
>> +
>> + @retval EFI_SUCCESS The IoMmuAccess is set for the memory range specified by DeviceAddress and Length.
>> + @retval EFI_INVALID_PARAMETER DeviceHandle is an invalid handle.
>> + @retval EFI_INVALID_PARAMETER Mapping is not a value that was returned by Map().
>> + @retval EFI_INVALID_PARAMETER IoMmuAccess specified an illegal combination of access.
>> + @retval EFI_UNSUPPORTED DeviceHandle is unknown by the IOMMU.
>> + @retval EFI_UNSUPPORTED The bit mask of IoMmuAccess is not supported by the IOMMU.
>> + @retval EFI_UNSUPPORTED The IOMMU does not support the memory range specified by Mapping.
>> + @retval EFI_OUT_OF_RESOURCES There are not enough resources available to modify the IOMMU access.
>> + @retval EFI_DEVICE_ERROR The IOMMU device reported an error while attempting the operation.
>> +
>> +**/
>> +EFI_STATUS
>> +EFIAPI
>> +IoMmuSetAttribute (
>> + IN EDKII_IOMMU_PROTOCOL *This,
>> + IN EFI_HANDLE DeviceHandle,
>> + IN VOID *Mapping,
>> + IN UINT64 IoMmuAccess
>> + )
>> +{
>> + return EFI_UNSUPPORTED;
>> +}
>> +
>> +EDKII_IOMMU_PROTOCOL mAmdSev = {
>> + EDKII_IOMMU_PROTOCOL_REVISION,
>> + IoMmuSetAttribute,
>> + IoMmuMap,
>> + IoMmuUnmap,
>> + IoMmuAllocateBuffer,
>> + IoMmuFreeBuffer,
>> +};
>> +
>> +/**
>> + Initialize Iommu Protocol.
>> +
>> +**/
>> +VOID
>> +EFIAPI
>> +AmdSevInstallIommuProtocol (
>> + VOID
>> + )
>> +{
>> + EFI_STATUS Status;
>> + EFI_HANDLE Handle;
>> +
>> + Handle = NULL;
>> + Status = gBS->InstallMultipleProtocolInterfaces (
>> + &Handle,
>> + &gEdkiiIoMmuProtocolGuid, &mAmdSev,
>> + NULL
>> + );
>> + ASSERT_EFI_ERROR (Status);
>> +}
>> diff --git a/OvmfPkg/AmdSevDxe/AmdSevMmio.c b/OvmfPkg/AmdSevDxe/AmdSevMmio.c
>> new file mode 100644
>> index 000000000000..b623f82b7baa
>> --- /dev/null
>> +++ b/OvmfPkg/AmdSevDxe/AmdSevMmio.c
>> @@ -0,0 +1,50 @@
>> +/** @file
>> +
>> + Implements routines to clear C-bit from MMIO Memory Range
>> +
>> + 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 "AmdSevMmio.h"
>> +
>> +/**
>> +
>> + 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 NonExistent
>> + memory space can gurantee that any MMIO mapped later will have C-bit cleared.
>> +*/
>> +VOID
>> +EFIAPI
>> +AmdSevClearEncMaskMmioRange (
>> + VOID
>> + )
>> +{
>> + EFI_STATUS Status;
>> + EFI_GCD_MEMORY_SPACE_DESCRIPTOR *AllDescMap;
>> + UINTN NumEntries;
>> + UINTN Index;
>> +
>> + Status = gDS->GetMemorySpaceMap (&NumEntries, &AllDescMap);
>> + if (Status == EFI_SUCCESS) {
>> + 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);
>> + }
>> + }
>
> (4) Right here I think you have a memory leak; gDS->GetMemorySpaceMap()
> allocates AllDescMap dynamically (on success). Please free it with
> FreePool().
>
>
> Regarding the IOMMU protocol implementation, I'm going to rely on
> Jiewen's review -- thank you Jiewen very much for that!
>
> With the above fixed:
>
> Reviewed-by: Laszlo Ersek <lersek@redhat.com>
>
> Thanks,
> Laszlo
>
>
>> + }
>> +}
>>
>
^ permalink raw reply [flat|nested] 42+ messages in thread
* Re: [RFC v4 06/13] OvmfPkg:AmdSevDxe: add AmdSevDxe driver
2017-05-11 15:53 ` Laszlo Ersek
@ 2017-05-11 17:43 ` Jordan Justen
2017-05-11 18:01 ` Brijesh Singh
2017-05-11 20:14 ` Laszlo Ersek
0 siblings, 2 replies; 42+ messages in thread
From: Jordan Justen @ 2017-05-11 17:43 UTC (permalink / raw)
To: Brijesh Singh, Laszlo Ersek, edk2-devel
Cc: Thomas.Lendacky, Jiewen Yao, leo.duran
On 2017-05-11 08:53:39, Laszlo Ersek wrote:
> (5) Please mention that the driver is being added to the APRIORI DXE
> file for a separate reason as well (not just for the early clearing of
> the C bit on MMIO/NonExistent): OvmfPkg's DXE phase modules that tailor
> their behavior to SEV presence will assume that the IOMMU protocol
> exported by this driver is available *at once*.
What other code depends on this being run apriori?
-Jordan
^ permalink raw reply [flat|nested] 42+ messages in thread
* Re: [RFC v4 06/13] OvmfPkg:AmdSevDxe: add AmdSevDxe driver
2017-05-11 17:43 ` Jordan Justen
@ 2017-05-11 18:01 ` Brijesh Singh
2017-05-15 17:47 ` Jordan Justen
2017-05-11 20:14 ` Laszlo Ersek
1 sibling, 1 reply; 42+ messages in thread
From: Brijesh Singh @ 2017-05-11 18:01 UTC (permalink / raw)
To: Jordan Justen, Laszlo Ersek, edk2-devel
Cc: brijesh.singh, Thomas.Lendacky, Jiewen Yao, leo.duran
On 05/11/2017 12:43 PM, Jordan Justen wrote:
> On 2017-05-11 08:53:39, Laszlo Ersek wrote:
>> (5) Please mention that the driver is being added to the APRIORI DXE
>> file for a separate reason as well (not just for the early clearing of
>> the C bit on MMIO/NonExistent): OvmfPkg's DXE phase modules that tailor
>> their behavior to SEV presence will assume that the IOMMU protocol
>> exported by this driver is available *at once*.
>
> What other code depends on this being run apriori?
>
We basically need some kind of guarantee that this driver is run before any other
drivers or libs access MMIO register/buffers. In additional to clearing encryption
bit from MMIO spaces, the driver also installs IOMMU protocol. So far, IOMMU protocol
is directly consumed by PciHostBridgeDxe driver and QemuFwCfgDxeLib.
To answer your question, any code which uses MMIO or DMA in Dxe phase depends on this
driver run as APRIORI.
-Brijesh
^ permalink raw reply [flat|nested] 42+ messages in thread
* Re: [RFC v4 06/13] OvmfPkg:AmdSevDxe: add AmdSevDxe driver
2017-05-11 18:01 ` Brijesh Singh
@ 2017-05-15 17:47 ` Jordan Justen
2017-05-16 12:04 ` Brijesh Singh
0 siblings, 1 reply; 42+ messages in thread
From: Jordan Justen @ 2017-05-15 17:47 UTC (permalink / raw)
To: Brijesh Singh, Laszlo Ersek, edk2-devel
Cc: Thomas.Lendacky, leo.duran, Jiewen Yao
On 2017-05-11 11:01:57, Brijesh Singh wrote:
>
>
> On 05/11/2017 12:43 PM, Jordan Justen wrote:
> > On 2017-05-11 08:53:39, Laszlo Ersek wrote:
> >> (5) Please mention that the driver is being added to the APRIORI DXE
> >> file for a separate reason as well (not just for the early clearing of
> >> the C bit on MMIO/NonExistent): OvmfPkg's DXE phase modules that tailor
> >> their behavior to SEV presence will assume that the IOMMU protocol
> >> exported by this driver is available *at once*.
> >
> > What other code depends on this being run apriori?
> >
>
> We basically need some kind of guarantee that this driver is run before any other
> drivers or libs access MMIO register/buffers. In additional to clearing encryption
> bit from MMIO spaces, the driver also installs IOMMU protocol. So far, IOMMU protocol
> is directly consumed by PciHostBridgeDxe driver and QemuFwCfgDxeLib.
What about adding a NULL protocol named
gOvmfIoMmuDetectionProtocolGuid? (Better name suggestions welcomed. :)
Then we can use this protocol in a depex where needed.
Maybe we should consider naming the driver IoMmuDxe instead?
I think the generic PciRoot bridge driver shouldn't need this in the
depex because it will not start until the BDS phase, and the IoMmuDxe
driver would have been dispatched by then.
-Jordan
> To answer your question, any code which uses MMIO or DMA in Dxe phase depends on this
> driver run as APRIORI.
>
> -Brijesh
> _______________________________________________
> edk2-devel mailing list
> edk2-devel@lists.01.org
> https://lists.01.org/mailman/listinfo/edk2-devel
^ permalink raw reply [flat|nested] 42+ messages in thread
* Re: [RFC v4 06/13] OvmfPkg:AmdSevDxe: add AmdSevDxe driver
2017-05-15 17:47 ` Jordan Justen
@ 2017-05-16 12:04 ` Brijesh Singh
2017-05-16 17:56 ` Jordan Justen
0 siblings, 1 reply; 42+ messages in thread
From: Brijesh Singh @ 2017-05-16 12:04 UTC (permalink / raw)
To: Jordan Justen, Laszlo Ersek, edk2-devel
Cc: Thomas.Lendacky, leo.duran, Jiewen Yao
Hi Jordan,
On 5/15/17 12:47 PM, Jordan Justen wrote:
> On 2017-05-11 11:01:57, Brijesh Singh wrote:
>>
>> We basically need some kind of guarantee that this driver is run before any other
>> drivers or libs access MMIO register/buffers. In additional to clearing encryption
>> bit from MMIO spaces, the driver also installs IOMMU protocol. So far, IOMMU protocol
>> is directly consumed by PciHostBridgeDxe driver and QemuFwCfgDxeLib.
> What about adding a NULL protocol named
> gOvmfIoMmuDetectionProtocolGuid? (Better name suggestions welcomed. :)
> Then we can use this protocol in a depex where needed.
It should be doable, If I find better name then I will use that :)
> Maybe we should consider naming the driver IoMmuDxe instead?
>
> I think the generic PciRoot bridge driver shouldn't need this in the
> depex because it will not start until the BDS phase, and the IoMmuDxe
> driver would have been dispatched by then.
Are you suggesting that we introduce a new IoMmuDxe driver and install
IOMMU protocol unconditionally ? I was hoping that we install IOMMU
protocol only when SEV is enabled. A non-SEV guest will still use the
old approach. I was minimizing changes into non-SEV code flow. Please
note that since AmdSevDxe driver does *two* things; a) clear C-bit from
MMIO b) installs IOMMU protocol hence I will not able to remove
AmdSevDxe completely. But I can remove IOMMU protocol installation part
from AmdSevDxe and move it into new IoMmuDxe driver. Please let me know
if this is what you are asking. thanks
-Brijesh
^ permalink raw reply [flat|nested] 42+ messages in thread
* Re: [RFC v4 06/13] OvmfPkg:AmdSevDxe: add AmdSevDxe driver
2017-05-16 12:04 ` Brijesh Singh
@ 2017-05-16 17:56 ` Jordan Justen
2017-05-16 20:25 ` Brijesh Singh
0 siblings, 1 reply; 42+ messages in thread
From: Jordan Justen @ 2017-05-16 17:56 UTC (permalink / raw)
To: Brijesh Singh, Laszlo Ersek, edk2-devel
Cc: Thomas.Lendacky, leo.duran, Jiewen Yao
On 2017-05-16 05:04:58, Brijesh Singh wrote:
> Hi Jordan,
>
> On 5/15/17 12:47 PM, Jordan Justen wrote:
> > On 2017-05-11 11:01:57, Brijesh Singh wrote:
> >>
> >> We basically need some kind of guarantee that this driver is run before any other
> >> drivers or libs access MMIO register/buffers. In additional to clearing encryption
> >> bit from MMIO spaces, the driver also installs IOMMU protocol. So far, IOMMU protocol
> >> is directly consumed by PciHostBridgeDxe driver and QemuFwCfgDxeLib.
> > What about adding a NULL protocol named
> > gOvmfIoMmuDetectionProtocolGuid? (Better name suggestions welcomed. :)
> > Then we can use this protocol in a depex where needed.
> It should be doable, If I find better name then I will use that :)
> > Maybe we should consider naming the driver IoMmuDxe instead?
> >
> > I think the generic PciRoot bridge driver shouldn't need this in the
> > depex because it will not start until the BDS phase, and the IoMmuDxe
> > driver would have been dispatched by then.
> Are you suggesting that we introduce a new IoMmuDxe driver and install
> IOMMU protocol unconditionally ?
No. I'm suggesting we have a new protocol that only exists to allow
dependency expressions to know that we've attempted to detect an IoMmu
implementation.
The driver would "install" the protocol with a NULL pointer regardless
of whether the IoMmu protocol was installed. Maybe
gOvmfIoMmuDetectionAttemptedProtocolGuid would be a better name?
The DXE fw-cfg library should then list this under depex. I think the
PCI Host bridge driver doesn't require the depex for the reason I
mentioned abobe.
The gEdkiiIoMmuProtocolGuid protocol would only be installed be
installed when detected like your patches currently do.
This method should allow the driver runtime order dependency to be
explicitly indicated.
Regarding the 'IoMmuDxe' name, I was suggesting that AmdSevDxe be
renamed to IoMmuDxe. Since we would be installing the 'we tried to
detect iommu' protocol, it probably makes sense to put all the iommu
implementation support into a single driver and only install the
'detection attempted' protocol it after trying to detect all supported
iommu implementations.
There could be an issue with this. FvbServicesRuntimeDxe.inf is in the
apriori currently if SMM_REQUIRE is set, so if it needs the iommu
treatment, then this wouldn't work. This driver does use MM I/O just
below 4GB. I don't think your current patches would change how this
driver runs since it doesn't use the PCI host bridge protocol, so I
guess it is ok?
(It would be nice to get FvbServicesRuntimeDxe.inf out of the apriori
too, but that is a separate issue.)
-Jordan
> I was hoping that we install IOMMU
> protocol only when SEV is enabled. A non-SEV guest will still use the
> old approach. I was minimizing changes into non-SEV code flow. Please
> note that since AmdSevDxe driver does *two* things; a) clear C-bit from
> MMIO b) installs IOMMU protocol hence I will not able to remove
> AmdSevDxe completely. But I can remove IOMMU protocol installation part
> from AmdSevDxe and move it into new IoMmuDxe driver. Please let me know
> if this is what you are asking. thanks
>
> -Brijesh
^ permalink raw reply [flat|nested] 42+ messages in thread
* Re: [RFC v4 06/13] OvmfPkg:AmdSevDxe: add AmdSevDxe driver
2017-05-16 17:56 ` Jordan Justen
@ 2017-05-16 20:25 ` Brijesh Singh
2017-05-18 8:50 ` Laszlo Ersek
0 siblings, 1 reply; 42+ messages in thread
From: Brijesh Singh @ 2017-05-16 20:25 UTC (permalink / raw)
To: Jordan Justen, Laszlo Ersek, edk2-devel
Cc: brijesh.singh, Thomas.Lendacky, leo.duran, Jiewen Yao
On 05/16/2017 12:56 PM, Jordan Justen wrote:
> On 2017-05-16 05:04:58, Brijesh Singh wrote:
>> Hi Jordan,
>>
>> On 5/15/17 12:47 PM, Jordan Justen wrote:
>>> On 2017-05-11 11:01:57, Brijesh Singh wrote:
>>>>
>>>> We basically need some kind of guarantee that this driver is run before any other
>>>> drivers or libs access MMIO register/buffers. In additional to clearing encryption
>>>> bit from MMIO spaces, the driver also installs IOMMU protocol. So far, IOMMU protocol
>>>> is directly consumed by PciHostBridgeDxe driver and QemuFwCfgDxeLib.
>>> What about adding a NULL protocol named
>>> gOvmfIoMmuDetectionProtocolGuid? (Better name suggestions welcomed. :)
>>> Then we can use this protocol in a depex where needed.
>> It should be doable, If I find better name then I will use that :)
>>> Maybe we should consider naming the driver IoMmuDxe instead?
>>>
>>> I think the generic PciRoot bridge driver shouldn't need this in the
>>> depex because it will not start until the BDS phase, and the IoMmuDxe
>>> driver would have been dispatched by then.
>> Are you suggesting that we introduce a new IoMmuDxe driver and install
>> IOMMU protocol unconditionally ?
>
> No. I'm suggesting we have a new protocol that only exists to allow
> dependency expressions to know that we've attempted to detect an IoMmu
> implementation.
>
Okay got it thanks.
> The driver would "install" the protocol with a NULL pointer regardless
> of whether the IoMmu protocol was installed. Maybe
> gOvmfIoMmuDetectionAttemptedProtocolGuid would be a better name?
>
> The DXE fw-cfg library should then list this under depex. I think the
> PCI Host bridge driver doesn't require the depex for the reason I
> mentioned abobe.
>
> The gEdkiiIoMmuProtocolGuid protocol would only be installed be
> installed when detected like your patches currently do.
>
> This method should allow the driver runtime order dependency to be
> explicitly indicated.
>
> Regarding the 'IoMmuDxe' name, I was suggesting that AmdSevDxe be
> renamed to IoMmuDxe. Since we would be installing the 'we tried to
> detect iommu' protocol, it probably makes sense to put all the iommu
> implementation support into a single driver and only install the
> 'detection attempted' protocol it after trying to detect all supported
> iommu implementations.
>
> There could be an issue with this. FvbServicesRuntimeDxe.inf is in the
> apriori currently if SMM_REQUIRE is set, so if it needs the iommu
> treatment, then this wouldn't work. This driver does use MM I/O just
> below 4GB. I don't think your current patches would change how this
> driver runs since it doesn't use the PCI host bridge protocol, so I
> guess it is ok?
>
We do need to ensure that AmdSevDxe runs before FvbServicesRuntimeDxe.inf.
As you rightly pointed, FvbServicesRuntimeDxe uses MM I/O below 4GB hence
we need to clear encryption attribute from MMIO space before QemuFlash
detection logic is invoked. In my patch set, I have listed AmdSevDxe.inf before
FvbServicesRuntimeDxe.inf to ensure that we clear the MMIO before QemuFlash
detection logic from FvbServicesRuntimeDxe.inf is invoked.
Here is fdt file snippet after my patches.
APRIORI DXE {
INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
INF MdeModulePkg/Universal/PCD/Dxe/Pcd.inf
INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf
!if $(SMM_REQUIRE) == FALSE
INF OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
!endif
}
> (It would be nice to get FvbServicesRuntimeDxe.inf out of the apriori
> too, but that is a separate issue.)
>
Yes, if we can move that out from Apriori then maybe also need to add some
kind of depex to ensure that it gets called after we clear memory encryption
bit from MMIO regions.
-Brijesh
^ permalink raw reply [flat|nested] 42+ messages in thread
* Re: [RFC v4 06/13] OvmfPkg:AmdSevDxe: add AmdSevDxe driver
2017-05-16 20:25 ` Brijesh Singh
@ 2017-05-18 8:50 ` Laszlo Ersek
0 siblings, 0 replies; 42+ messages in thread
From: Laszlo Ersek @ 2017-05-18 8:50 UTC (permalink / raw)
To: Brijesh Singh, Jordan Justen, edk2-devel
Cc: Thomas.Lendacky, leo.duran, Jiewen Yao
On 05/16/17 22:25, Brijesh Singh wrote:
>
>
> On 05/16/2017 12:56 PM, Jordan Justen wrote:
>> On 2017-05-16 05:04:58, Brijesh Singh wrote:
>>> Hi Jordan,
>>>
>>> On 5/15/17 12:47 PM, Jordan Justen wrote:
>>>> On 2017-05-11 11:01:57, Brijesh Singh wrote:
>>>>>
>>>>> We basically need some kind of guarantee that this driver is run
>>>>> before any other
>>>>> drivers or libs access MMIO register/buffers. In additional to
>>>>> clearing encryption
>>>>> bit from MMIO spaces, the driver also installs IOMMU protocol. So
>>>>> far, IOMMU protocol
>>>>> is directly consumed by PciHostBridgeDxe driver and QemuFwCfgDxeLib.
>>>> What about adding a NULL protocol named
>>>> gOvmfIoMmuDetectionProtocolGuid? (Better name suggestions welcomed. :)
>>>> Then we can use this protocol in a depex where needed.
>>> It should be doable, If I find better name then I will use that :)
>>>> Maybe we should consider naming the driver IoMmuDxe instead?
>>>>
>>>> I think the generic PciRoot bridge driver shouldn't need this in the
>>>> depex because it will not start until the BDS phase, and the IoMmuDxe
>>>> driver would have been dispatched by then.
>>> Are you suggesting that we introduce a new IoMmuDxe driver and install
>>> IOMMU protocol unconditionally ?
>>
>> No. I'm suggesting we have a new protocol that only exists to allow
>> dependency expressions to know that we've attempted to detect an IoMmu
>> implementation.
>>
>
> Okay got it thanks.
>
>> The driver would "install" the protocol with a NULL pointer regardless
>> of whether the IoMmu protocol was installed. Maybe
>> gOvmfIoMmuDetectionAttemptedProtocolGuid would be a better name?
>>
>> The DXE fw-cfg library should then list this under depex. I think the
>> PCI Host bridge driver doesn't require the depex for the reason I
>> mentioned abobe.
>>
>> The gEdkiiIoMmuProtocolGuid protocol would only be installed be
>> installed when detected like your patches currently do.
>>
>> This method should allow the driver runtime order dependency to be
>> explicitly indicated.
>>
>> Regarding the 'IoMmuDxe' name, I was suggesting that AmdSevDxe be
>> renamed to IoMmuDxe. Since we would be installing the 'we tried to
>> detect iommu' protocol, it probably makes sense to put all the iommu
>> implementation support into a single driver and only install the
>> 'detection attempted' protocol it after trying to detect all supported
>> iommu implementations.
>>
>> There could be an issue with this. FvbServicesRuntimeDxe.inf is in the
>> apriori currently if SMM_REQUIRE is set, so if it needs the iommu
>> treatment, then this wouldn't work. This driver does use MM I/O just
>> below 4GB. I don't think your current patches would change how this
>> driver runs since it doesn't use the PCI host bridge protocol, so I
>> guess it is ok?
>>
>
> We do need to ensure that AmdSevDxe runs before FvbServicesRuntimeDxe.inf.
> As you rightly pointed, FvbServicesRuntimeDxe uses MM I/O below 4GB hence
> we need to clear encryption attribute from MMIO space before QemuFlash
> detection logic is invoked. In my patch set, I have listed AmdSevDxe.inf
> before
> FvbServicesRuntimeDxe.inf to ensure that we clear the MMIO before QemuFlash
> detection logic from FvbServicesRuntimeDxe.inf is invoked.
>
> Here is fdt file snippet after my patches.
>
> APRIORI DXE {
> INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
> INF MdeModulePkg/Universal/PCD/Dxe/Pcd.inf
> INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf
> !if $(SMM_REQUIRE) == FALSE
> INF OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
> !endif
> }
>
>
>> (It would be nice to get FvbServicesRuntimeDxe.inf out of the apriori
>> too, but that is a separate issue.)
>>
>
> Yes, if we can move that out from Apriori then maybe also need to add some
> kind of depex to ensure that it gets called after we clear memory
> encryption
> bit from MMIO regions.
Adding a couple of points down here.
(1) As Brijesh points out, AmdSevDxe does two things.
The second thing (the IOMMU protocol implementation) could be detached,
yes, and as Jordan suggests, we could introduce a synthetic /
placeholder protocol as well, for dependent modules to depend on.
DEPEXes can use "OR" operators (see "Table 21. Dependency Expression
Opcode Summary" in Vol2 of PI 1.5), so a library instance could impart
client modules with an alternative dependency on either the real IOMMU
protocol thing or the placeholder thing. AmdSevDxe would then look for
the SEV capability, and install the appropriate (IOMMU or placeholder)
protocol.
However, the other thing that AmdSevDxe provides doesn't look possible
to move out of the APRIORI DXE file. Clearing the C bit on all
nonexistent GCD ranges, and on the MMIO GCD ranges (which at that point
all come from PEI HOBs) enables *all* DXE drivers to go about their MMIO
range additions and allocations without knowing about SEV. I think
keeping generic MMIO-using DXE drivers blissfully unaware of SEV is an
important design goal.
(2) QemuFlashFvbServicesRuntimeDxe is in the APRIORI DXE file when
SMM_REQUIRE is *clear*, not when it is set.
When SMM_REQUIRE is set, then pflash is a hard requirement (*), and the
build includes only QemuFlashFvbServicesRuntimeDxe -- namely, the SMM
build thereof --; the build doesn't include EmuVariableFvbRuntimeDxe.
Therefore only one FVB provider exists, so there's no need to enforce
any dispatch order between "competing" FVB providers.
With SMM_REQUIRE being *clear*, there are two competing FVB providers,
and QemuFlashFvbServicesRuntimeDxe must get priority over
EmuVariableFvbRuntimeDxe. This is why we add
QemuFlashFvbServicesRuntimeDxe to the APRIORI DXE file in that case.
Please see commit 46df0216b0ed ("OvmfPkg: pull in SMM-based variable
driver stack", 2015-11-30).
(*) Dynamically degrading flash access from pflash to emulated would be
a security bug. This is why SMM_REQUIRE is called SMM_REQUIRE and not
SMM_ENABLE, and why hanging the SMM_REQUIRE build when pflash is missing
is the right thing.
Thanks,
Laszlo
^ permalink raw reply [flat|nested] 42+ messages in thread
* Re: [RFC v4 06/13] OvmfPkg:AmdSevDxe: add AmdSevDxe driver
2017-05-11 17:43 ` Jordan Justen
2017-05-11 18:01 ` Brijesh Singh
@ 2017-05-11 20:14 ` Laszlo Ersek
1 sibling, 0 replies; 42+ messages in thread
From: Laszlo Ersek @ 2017-05-11 20:14 UTC (permalink / raw)
To: Jordan Justen, Brijesh Singh, edk2-devel
Cc: Thomas.Lendacky, Jiewen Yao, leo.duran
On 05/11/17 19:43, Jordan Justen wrote:
> On 2017-05-11 08:53:39, Laszlo Ersek wrote:
>> (5) Please mention that the driver is being added to the APRIORI DXE
>> file for a separate reason as well (not just for the early clearing of
>> the C bit on MMIO/NonExistent): OvmfPkg's DXE phase modules that tailor
>> their behavior to SEV presence will assume that the IOMMU protocol
>> exported by this driver is available *at once*.
>
> What other code depends on this being run apriori?
Minimally, every module that is a client of the DXE-phase fw-cfg library
instance. That library instance uses the EdkII IOMMU protocol for
allocating and freeing the non-encrypted bounce buffer needed for the
fw_cfg DMA transfer. The protocol is only used / needed when SEV is
detected.
Thanks
Laszlo
^ permalink raw reply [flat|nested] 42+ messages in thread
* Re: [RFC v4 06/13] OvmfPkg:AmdSevDxe: add AmdSevDxe driver
2017-05-11 15:19 ` Laszlo Ersek
2017-05-11 15:53 ` Laszlo Ersek
@ 2017-05-11 18:12 ` Brijesh Singh
1 sibling, 0 replies; 42+ messages in thread
From: Brijesh Singh @ 2017-05-11 18:12 UTC (permalink / raw)
To: Laszlo Ersek, edk2-devel
Cc: brijesh.singh, Thomas.Lendacky, Jordan Justen, Jiewen Yao,
leo.duran
On 05/11/2017 10:19 AM, Laszlo Ersek wrote:
>
> (1) Please mention that the C bit is cleared for MMIO GCD entries in
> order to cover the ranges that were added during the PEI phase (through
> memory resource descriptor HOBs).
>
> Also mention that the NonExistent ranges are processed in order to
> cover, in advance, MMIO ranges added later in the DXE phase by various
> device drivers, via the appropriate DXE memory space services.
>
> Finally, please mention that the approach is not transparent for later
> addition of system memory ranges to the GCD memory space map. (Such
> ranges should be encrypted.) OVMF does not do such a thing at the
> moment, so this approach should be OK.
>
> I think we should also credit Jiewen for both ideas, namely the IOMMU
> stuff and the handling of NonExistent ranges (in anticipation of future
> MMIO additions), so please add
>
> Suggested-by: Jiewen Yao <jiewen.yao@intel.com>
>
Agreed :)
I will definitely give credit to Jiewen for it. Additionally, I borrowed
the IOMMU driver implementation from Jiewen's sample driver hence I believe I've
retained the Intel copyright in both header and source file, if not then I will
make sure to include it in next patch.
[snip...]
>
> (4) Right here I think you have a memory leak; gDS->GetMemorySpaceMap()
> allocates AllDescMap dynamically (on success). Please free it with
> FreePool().
>
Ah good point. I will make sure to free the memory.
-Brijesh
^ permalink raw reply [flat|nested] 42+ messages in thread
* [RFC v4 07/13] OvmfPkg/QemuFwCfgLib: Provide Pei and Dxe specific library
2017-05-10 22:09 [RFC v4 00/13] x86: Secure Encrypted Virtualization (AMD) Brijesh Singh
` (5 preceding siblings ...)
2017-05-10 22:09 ` [RFC v4 06/13] OvmfPkg:AmdSevDxe: add AmdSevDxe driver Brijesh Singh
@ 2017-05-10 22:09 ` Brijesh Singh
2017-05-11 15:40 ` Laszlo Ersek
2017-05-10 22:09 ` [RFC v4 08/13] OvmfPkg/QemuFwCfgLib: Prepare for SEV support Brijesh Singh
` (5 subsequent siblings)
12 siblings, 1 reply; 42+ messages in thread
From: Brijesh Singh @ 2017-05-10 22:09 UTC (permalink / raw)
To: edk2-devel
Cc: Thomas.Lendacky, leo.duran, Brijesh Singh, Jordan Justen,
Laszlo Ersek
Current QemuFwCfgLib.inf is used in both Pei and Dxe phases. Add Pei
and Dxe inf file to provide a seperate QemuFwCfgLib instances for Pei
and Dxe phases.
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
---
OvmfPkg/OvmfPkgIa32.dsc | 3 ++-
OvmfPkg/OvmfPkgIa32X64.dsc | 3 ++-
OvmfPkg/OvmfPkgX64.dsc | 3 ++-
OvmfPkg/Library/QemuFwCfgLib/{QemuFwCfgLib.inf => QemuFwCfgDxeLib.inf} | 6 +++---
OvmfPkg/Library/QemuFwCfgLib/{QemuFwCfgLib.inf => QemuFwCfgPeiLib.inf} | 6 +++---
OvmfPkg/Library/QemuFwCfgLib/{QemuFwCfgPeiDxe.c => QemuFwCfgDxe.c} | 0
OvmfPkg/Library/QemuFwCfgLib/{QemuFwCfgPeiDxe.c => QemuFwCfgPei.c} | 0
7 files changed, 12 insertions(+), 9 deletions(-)
diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc
index 139d54aa010e..cde3d43e39a9 100644
--- a/OvmfPkg/OvmfPkgIa32.dsc
+++ b/OvmfPkg/OvmfPkgIa32.dsc
@@ -140,7 +140,7 @@ [LibraryClasses]
DpcLib|MdeModulePkg/Library/DxeDpcLib/DxeDpcLib.inf
UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf
SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf
- QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
+ QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf
LoadLinuxLib|OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.inf
MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
@@ -257,6 +257,7 @@ [LibraryClasses.common.PEIM]
CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf
MpInitLib|UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf
QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/PeiQemuFwCfgS3LibFwCfg.inf
+ QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
[LibraryClasses.common.DXE_CORE]
HobLib|MdePkg/Library/DxeCoreHobLib/DxeCoreHobLib.inf
diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
index ee6f98d68b73..8aa72718d065 100644
--- a/OvmfPkg/OvmfPkgIa32X64.dsc
+++ b/OvmfPkg/OvmfPkgIa32X64.dsc
@@ -145,7 +145,7 @@ [LibraryClasses]
DpcLib|MdeModulePkg/Library/DxeDpcLib/DxeDpcLib.inf
UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf
SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf
- QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
+ QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf
LoadLinuxLib|OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.inf
MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
@@ -262,6 +262,7 @@ [LibraryClasses.common.PEIM]
CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf
MpInitLib|UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf
QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/PeiQemuFwCfgS3LibFwCfg.inf
+ QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
[LibraryClasses.common.DXE_CORE]
HobLib|MdePkg/Library/DxeCoreHobLib/DxeCoreHobLib.inf
diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
index b5f26e06e60b..963d394662ab 100644
--- a/OvmfPkg/OvmfPkgX64.dsc
+++ b/OvmfPkg/OvmfPkgX64.dsc
@@ -145,7 +145,7 @@ [LibraryClasses]
DpcLib|MdeModulePkg/Library/DxeDpcLib/DxeDpcLib.inf
UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf
SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf
- QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
+ QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf
LoadLinuxLib|OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.inf
MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
@@ -262,6 +262,7 @@ [LibraryClasses.common.PEIM]
CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf
MpInitLib|UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf
QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/PeiQemuFwCfgS3LibFwCfg.inf
+ QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
[LibraryClasses.common.DXE_CORE]
HobLib|MdePkg/Library/DxeCoreHobLib/DxeCoreHobLib.inf
diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
similarity index 83%
copy from OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
copy to OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
index 689476032d39..346bb881ffc1 100644
--- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
+++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
@@ -19,10 +19,10 @@
[Defines]
INF_VERSION = 0x00010005
BASE_NAME = QemuFwCfgLib
- FILE_GUID = fdd53716-31e1-4acc-9007-8bd5d877c96f
+ FILE_GUID = 80474090-55e7-4c28-b25c-9f236ba41f28
MODULE_TYPE = BASE
VERSION_STRING = 1.0
- LIBRARY_CLASS = QemuFwCfgLib|PEIM DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER
+ LIBRARY_CLASS = QemuFwCfgLib|DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER
CONSTRUCTOR = QemuFwCfgInitialize
@@ -35,7 +35,7 @@ [Defines]
[Sources]
QemuFwCfgLibInternal.h
QemuFwCfgLib.c
- QemuFwCfgPeiDxe.c
+ QemuFwCfgDxe.c
[Packages]
MdePkg/MdePkg.dec
diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
similarity index 83%
rename from OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
rename to OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
index 689476032d39..4f966a85088a 100644
--- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
+++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
@@ -19,10 +19,10 @@
[Defines]
INF_VERSION = 0x00010005
BASE_NAME = QemuFwCfgLib
- FILE_GUID = fdd53716-31e1-4acc-9007-8bd5d877c96f
+ FILE_GUID = ddd4f5f0-5304-42a8-9efa-d14bf11a3533
MODULE_TYPE = BASE
VERSION_STRING = 1.0
- LIBRARY_CLASS = QemuFwCfgLib|PEIM DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER
+ LIBRARY_CLASS = QemuFwCfgLib|PEIM
CONSTRUCTOR = QemuFwCfgInitialize
@@ -35,7 +35,7 @@ [Defines]
[Sources]
QemuFwCfgLibInternal.h
QemuFwCfgLib.c
- QemuFwCfgPeiDxe.c
+ QemuFwCfgPei.c
[Packages]
MdePkg/MdePkg.dec
diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiDxe.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c
similarity index 100%
copy from OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiDxe.c
copy to OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c
diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiDxe.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c
similarity index 100%
rename from OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiDxe.c
rename to OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c
--
2.7.4
^ permalink raw reply related [flat|nested] 42+ messages in thread
* Re: [RFC v4 07/13] OvmfPkg/QemuFwCfgLib: Provide Pei and Dxe specific library
2017-05-10 22:09 ` [RFC v4 07/13] OvmfPkg/QemuFwCfgLib: Provide Pei and Dxe specific library Brijesh Singh
@ 2017-05-11 15:40 ` Laszlo Ersek
2017-05-11 18:16 ` Brijesh Singh
0 siblings, 1 reply; 42+ messages in thread
From: Laszlo Ersek @ 2017-05-11 15:40 UTC (permalink / raw)
To: Brijesh Singh, edk2-devel; +Cc: Thomas.Lendacky, leo.duran, Jordan Justen
comments below:
On 05/11/17 00:09, Brijesh Singh wrote:
> Current QemuFwCfgLib.inf is used in both Pei and Dxe phases. Add Pei
> and Dxe inf file to provide a seperate QemuFwCfgLib instances for Pei
> and Dxe phases.
>
>
> Cc: Jordan Justen <jordan.l.justen@intel.com>
> Cc: Laszlo Ersek <lersek@redhat.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
> ---
> OvmfPkg/OvmfPkgIa32.dsc | 3 ++-
> OvmfPkg/OvmfPkgIa32X64.dsc | 3 ++-
> OvmfPkg/OvmfPkgX64.dsc | 3 ++-
> OvmfPkg/Library/QemuFwCfgLib/{QemuFwCfgLib.inf => QemuFwCfgDxeLib.inf} | 6 +++---
> OvmfPkg/Library/QemuFwCfgLib/{QemuFwCfgLib.inf => QemuFwCfgPeiLib.inf} | 6 +++---
> OvmfPkg/Library/QemuFwCfgLib/{QemuFwCfgPeiDxe.c => QemuFwCfgDxe.c} | 0
> OvmfPkg/Library/QemuFwCfgLib/{QemuFwCfgPeiDxe.c => QemuFwCfgPei.c} | 0
> 7 files changed, 12 insertions(+), 9 deletions(-)
>
> diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc
> index 139d54aa010e..cde3d43e39a9 100644
> --- a/OvmfPkg/OvmfPkgIa32.dsc
> +++ b/OvmfPkg/OvmfPkgIa32.dsc
> @@ -140,7 +140,7 @@ [LibraryClasses]
> DpcLib|MdeModulePkg/Library/DxeDpcLib/DxeDpcLib.inf
> UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf
> SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf
> - QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
> + QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
> VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf
> LoadLinuxLib|OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.inf
> MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
> @@ -257,6 +257,7 @@ [LibraryClasses.common.PEIM]
> CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf
> MpInitLib|UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf
> QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/PeiQemuFwCfgS3LibFwCfg.inf
> + QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
>
> [LibraryClasses.common.DXE_CORE]
> HobLib|MdePkg/Library/DxeCoreHobLib/DxeCoreHobLib.inf
> diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
> index ee6f98d68b73..8aa72718d065 100644
> --- a/OvmfPkg/OvmfPkgIa32X64.dsc
> +++ b/OvmfPkg/OvmfPkgIa32X64.dsc
> @@ -145,7 +145,7 @@ [LibraryClasses]
> DpcLib|MdeModulePkg/Library/DxeDpcLib/DxeDpcLib.inf
> UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf
> SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf
> - QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
> + QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
> VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf
> LoadLinuxLib|OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.inf
> MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
> @@ -262,6 +262,7 @@ [LibraryClasses.common.PEIM]
> CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf
> MpInitLib|UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf
> QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/PeiQemuFwCfgS3LibFwCfg.inf
> + QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
>
> [LibraryClasses.common.DXE_CORE]
> HobLib|MdePkg/Library/DxeCoreHobLib/DxeCoreHobLib.inf
> diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
> index b5f26e06e60b..963d394662ab 100644
> --- a/OvmfPkg/OvmfPkgX64.dsc
> +++ b/OvmfPkg/OvmfPkgX64.dsc
> @@ -145,7 +145,7 @@ [LibraryClasses]
> DpcLib|MdeModulePkg/Library/DxeDpcLib/DxeDpcLib.inf
> UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf
> SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf
> - QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
> + QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
> VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf
> LoadLinuxLib|OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.inf
> MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
> @@ -262,6 +262,7 @@ [LibraryClasses.common.PEIM]
> CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf
> MpInitLib|UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf
> QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/PeiQemuFwCfgS3LibFwCfg.inf
> + QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
>
> [LibraryClasses.common.DXE_CORE]
> HobLib|MdePkg/Library/DxeCoreHobLib/DxeCoreHobLib.inf
> diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
> similarity index 83%
> copy from OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
> copy to OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
> index 689476032d39..346bb881ffc1 100644
> --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
> +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
> @@ -19,10 +19,10 @@
> [Defines]
> INF_VERSION = 0x00010005
> BASE_NAME = QemuFwCfgLib
(1) Please update this to "QemuFwCfgDxeLib".
> - FILE_GUID = fdd53716-31e1-4acc-9007-8bd5d877c96f
> + FILE_GUID = 80474090-55e7-4c28-b25c-9f236ba41f28
> MODULE_TYPE = BASE
> VERSION_STRING = 1.0
> - LIBRARY_CLASS = QemuFwCfgLib|PEIM DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER
> + LIBRARY_CLASS = QemuFwCfgLib|DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER
>
> CONSTRUCTOR = QemuFwCfgInitialize
>
> @@ -35,7 +35,7 @@ [Defines]
> [Sources]
> QemuFwCfgLibInternal.h
> QemuFwCfgLib.c
> - QemuFwCfgPeiDxe.c
> + QemuFwCfgDxe.c
>
> [Packages]
> MdePkg/MdePkg.dec
> diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
> similarity index 83%
> rename from OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
> rename to OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
> index 689476032d39..4f966a85088a 100644
> --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.inf
> +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
> @@ -19,10 +19,10 @@
> [Defines]
> INF_VERSION = 0x00010005
> BASE_NAME = QemuFwCfgLib
(2) Please update this to "QemuFwCfgPeiLib".
With those changes:
Reviewed-by: Laszlo Ersek <lersek@redhat.com>
Thanks,
Laszlo
> - FILE_GUID = fdd53716-31e1-4acc-9007-8bd5d877c96f
> + FILE_GUID = ddd4f5f0-5304-42a8-9efa-d14bf11a3533
> MODULE_TYPE = BASE
> VERSION_STRING = 1.0
> - LIBRARY_CLASS = QemuFwCfgLib|PEIM DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER
> + LIBRARY_CLASS = QemuFwCfgLib|PEIM
>
> CONSTRUCTOR = QemuFwCfgInitialize
>
> @@ -35,7 +35,7 @@ [Defines]
> [Sources]
> QemuFwCfgLibInternal.h
> QemuFwCfgLib.c
> - QemuFwCfgPeiDxe.c
> + QemuFwCfgPei.c
>
> [Packages]
> MdePkg/MdePkg.dec
> diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiDxe.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c
> similarity index 100%
> copy from OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiDxe.c
> copy to OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c
> diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiDxe.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c
> similarity index 100%
> rename from OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiDxe.c
> rename to OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c
>
^ permalink raw reply [flat|nested] 42+ messages in thread
* Re: [RFC v4 07/13] OvmfPkg/QemuFwCfgLib: Provide Pei and Dxe specific library
2017-05-11 15:40 ` Laszlo Ersek
@ 2017-05-11 18:16 ` Brijesh Singh
0 siblings, 0 replies; 42+ messages in thread
From: Brijesh Singh @ 2017-05-11 18:16 UTC (permalink / raw)
To: Laszlo Ersek, edk2-devel
Cc: brijesh.singh, Thomas.Lendacky, leo.duran, Jordan Justen
On 05/11/2017 10:40 AM, Laszlo Ersek wrote:
[snip...]
>> BASE_NAME = QemuFwCfgLib
>
> (1) Please update this to "QemuFwCfgDxeLib".
>
Done.
[snip..]
>> BASE_NAME = QemuFwCfgLib
>
> (2) Please update this to "QemuFwCfgPeiLib".
>
Done. thanks
-Brijesh
^ permalink raw reply [flat|nested] 42+ messages in thread
* [RFC v4 08/13] OvmfPkg/QemuFwCfgLib: Prepare for SEV support
2017-05-10 22:09 [RFC v4 00/13] x86: Secure Encrypted Virtualization (AMD) Brijesh Singh
` (6 preceding siblings ...)
2017-05-10 22:09 ` [RFC v4 07/13] OvmfPkg/QemuFwCfgLib: Provide Pei and Dxe specific library Brijesh Singh
@ 2017-05-10 22:09 ` Brijesh Singh
2017-05-11 15:57 ` Laszlo Ersek
2017-05-10 22:09 ` [RFC v4 09/13] OvmfPkg/QemuFwCfgLib: Implement SEV internal function for SEC phase Brijesh Singh
` (4 subsequent siblings)
12 siblings, 1 reply; 42+ messages in thread
From: Brijesh Singh @ 2017-05-10 22:09 UTC (permalink / raw)
To: edk2-devel
Cc: Thomas.Lendacky, leo.duran, Brijesh Singh, Jordan Justen,
Laszlo Ersek
Add SEV specific internal functions which will be used while intergrating
the SEV support into QemuFwCfgLib.
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
---
OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibInternal.h | 36 ++++++++++++++++++++
1 file changed, 36 insertions(+)
diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibInternal.h b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibInternal.h
index 6e87c625102e..87573ff2fbe3 100644
--- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibInternal.h
+++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibInternal.h
@@ -43,4 +43,40 @@ InternalQemuFwCfgDmaIsAvailable (
VOID
);
+/**
+ Returns a boolean indicating whether SEV support is enabled
+
+ @retval TRUE SEV is enabled
+ @retval FALSE SEV is disabled
+**/
+BOOLEAN
+InternalQemuFwCfgSevIsEnabled (
+ VOID
+ );
+
+/**
+ Allocate a bounce buffer for SEV DMA.
+
+ @param[in] NumPage Number of pages.
+ @param[out] Buffer Allocated DMA Buffer pointer
+
+**/
+VOID
+InternalQemuFwCfgSevDmaAllocateBuffer (
+ IN UINT32 NumPages,
+ OUT VOID **Buffer
+ );
+
+/**
+ Free the DMA buffer allocated using InternalQemuFwCfgSevDmaAllocateBuffer
+
+ @param[in] NumPage Number of pages.
+ @param[in] Buffer DMA Buffer pointer
+
+**/
+VOID
+InternalQemuFwCfgSevDmaFreeBuffer (
+ IN VOID *Buffer,
+ IN UINT32 NumPages
+ );
#endif
--
2.7.4
^ permalink raw reply related [flat|nested] 42+ messages in thread
* Re: [RFC v4 08/13] OvmfPkg/QemuFwCfgLib: Prepare for SEV support
2017-05-10 22:09 ` [RFC v4 08/13] OvmfPkg/QemuFwCfgLib: Prepare for SEV support Brijesh Singh
@ 2017-05-11 15:57 ` Laszlo Ersek
0 siblings, 0 replies; 42+ messages in thread
From: Laszlo Ersek @ 2017-05-11 15:57 UTC (permalink / raw)
To: Brijesh Singh, edk2-devel; +Cc: Thomas.Lendacky, leo.duran, Jordan Justen
On 05/11/17 00:09, Brijesh Singh wrote:
> Add SEV specific internal functions which will be used while intergrating
> the SEV support into QemuFwCfgLib.
>
>
> Cc: Jordan Justen <jordan.l.justen@intel.com>
> Cc: Laszlo Ersek <lersek@redhat.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
> ---
> OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibInternal.h | 36 ++++++++++++++++++++
> 1 file changed, 36 insertions(+)
>
> diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibInternal.h b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibInternal.h
> index 6e87c625102e..87573ff2fbe3 100644
> --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibInternal.h
> +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibInternal.h
> @@ -43,4 +43,40 @@ InternalQemuFwCfgDmaIsAvailable (
> VOID
> );
>
> +/**
> + Returns a boolean indicating whether SEV support is enabled
> +
> + @retval TRUE SEV is enabled
> + @retval FALSE SEV is disabled
> +**/
> +BOOLEAN
> +InternalQemuFwCfgSevIsEnabled (
> + VOID
> + );
> +
> +/**
> + Allocate a bounce buffer for SEV DMA.
> +
> + @param[in] NumPage Number of pages.
> + @param[out] Buffer Allocated DMA Buffer pointer
> +
> +**/
> +VOID
> +InternalQemuFwCfgSevDmaAllocateBuffer (
> + IN UINT32 NumPages,
> + OUT VOID **Buffer
> + );
Can you reorder the function parameters here? So that the order match
the one in InternalQemuFwCfgSevDmaFreeBuffer() below.
With that fixed,
Reviewed-by: Laszlo Ersek <lersek@redhat.com>
Thanks,
Laszlo
> +
> +/**
> + Free the DMA buffer allocated using InternalQemuFwCfgSevDmaAllocateBuffer
> +
> + @param[in] NumPage Number of pages.
> + @param[in] Buffer DMA Buffer pointer
> +
> +**/
> +VOID
> +InternalQemuFwCfgSevDmaFreeBuffer (
> + IN VOID *Buffer,
> + IN UINT32 NumPages
> + );
> #endif
>
^ permalink raw reply [flat|nested] 42+ messages in thread
* [RFC v4 09/13] OvmfPkg/QemuFwCfgLib: Implement SEV internal function for SEC phase
2017-05-10 22:09 [RFC v4 00/13] x86: Secure Encrypted Virtualization (AMD) Brijesh Singh
` (7 preceding siblings ...)
2017-05-10 22:09 ` [RFC v4 08/13] OvmfPkg/QemuFwCfgLib: Prepare for SEV support Brijesh Singh
@ 2017-05-10 22:09 ` Brijesh Singh
2017-05-11 16:24 ` Laszlo Ersek
2017-05-10 22:09 ` [RFC v4 10/13] OvmfPkg/QemuFwCfgLib: Implement SEV internal functions for PEI phase Brijesh Singh
` (3 subsequent siblings)
12 siblings, 1 reply; 42+ messages in thread
From: Brijesh Singh @ 2017-05-10 22:09 UTC (permalink / raw)
To: edk2-devel
Cc: Thomas.Lendacky, leo.duran, Brijesh Singh, Jordan Justen,
Laszlo Ersek
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
---
OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf | 1 +
OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSec.c | 57 ++++++++++++++++++++
2 files changed, 58 insertions(+)
diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf
index 7a96575d1851..b782ac6c0aa2 100644
--- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf
+++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf
@@ -45,4 +45,5 @@ [LibraryClasses]
DebugLib
IoLib
MemoryAllocationLib
+ MemEncryptSevLib
diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSec.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSec.c
index 465ccbe90dad..cd04cc814063 100644
--- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSec.c
+++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSec.c
@@ -6,6 +6,7 @@
Copyright (C) 2013, Red Hat, Inc.
Copyright (c) 2011 - 2013, Intel Corporation. All rights reserved.<BR>
+ 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
@@ -18,6 +19,7 @@
#include <Library/DebugLib.h>
#include <Library/QemuFwCfgLib.h>
+#include <Library/MemEncryptSevLib.h>
#include "QemuFwCfgLibInternal.h"
@@ -94,3 +96,58 @@ InternalQemuFwCfgDmaIsAvailable (
{
return FALSE;
}
+
+/**
+
+ Returns a boolean indicating whether SEV is enabled
+
+ @retval TRUE SEV is enabled
+ @retval FALSE SEV is disabled
+**/
+BOOLEAN
+InternalQemuFwCfgSevIsEnabled (
+ VOID
+ )
+{
+ return MemEncryptSevIsEnabled ();
+}
+
+/**
+ Allocate a bounce buffer for SEV DMA.
+
+ @param[in] NumPage Number of pages.
+ @param[out] Buffer Allocated DMA Buffer pointer
+
+**/
+VOID
+InternalQemuFwCfgSevDmaAllocateBuffer (
+ IN UINT32 NumPages,
+ OUT VOID **Buffer
+ )
+{
+ //
+ // We should never reach here
+ //
+ ASSERT (FALSE);
+ CpuDeadLoop ();
+}
+
+/**
+ Free the DMA buffer allocated using InternalQemuFwCfgSevDmaAllocateBuffer
+
+ @param[in] NumPage Number of pages.
+ @param[in] Buffer DMA Buffer pointer
+
+**/
+VOID
+InternalQemuFwCfgSevDmaFreeBuffer (
+ IN VOID *Buffer,
+ IN UINT32 NumPages
+ )
+{
+ //
+ // We should never reach here
+ //
+ ASSERT (FALSE);
+ CpuDeadLoop ();
+}
--
2.7.4
^ permalink raw reply related [flat|nested] 42+ messages in thread
* Re: [RFC v4 09/13] OvmfPkg/QemuFwCfgLib: Implement SEV internal function for SEC phase
2017-05-10 22:09 ` [RFC v4 09/13] OvmfPkg/QemuFwCfgLib: Implement SEV internal function for SEC phase Brijesh Singh
@ 2017-05-11 16:24 ` Laszlo Ersek
2017-05-11 18:21 ` Brijesh Singh
0 siblings, 1 reply; 42+ messages in thread
From: Laszlo Ersek @ 2017-05-11 16:24 UTC (permalink / raw)
To: Brijesh Singh, edk2-devel; +Cc: Thomas.Lendacky, leo.duran, Jordan Justen
On 05/11/17 00:09, Brijesh Singh wrote:
> Cc: Jordan Justen <jordan.l.justen@intel.com>
> Cc: Laszlo Ersek <lersek@redhat.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
> ---
> OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf | 1 +
> OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSec.c | 57 ++++++++++++++++++++
> 2 files changed, 58 insertions(+)
>
> diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf
> index 7a96575d1851..b782ac6c0aa2 100644
> --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf
> +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf
> @@ -45,4 +45,5 @@ [LibraryClasses]
> DebugLib
> IoLib
> MemoryAllocationLib
> + MemEncryptSevLib
This will not compile. More below.
>
> diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSec.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSec.c
> index 465ccbe90dad..cd04cc814063 100644
> --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSec.c
> +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSec.c
> @@ -6,6 +6,7 @@
>
> Copyright (C) 2013, Red Hat, Inc.
> Copyright (c) 2011 - 2013, Intel Corporation. All rights reserved.<BR>
> + 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
> @@ -18,6 +19,7 @@
>
> #include <Library/DebugLib.h>
> #include <Library/QemuFwCfgLib.h>
> +#include <Library/MemEncryptSevLib.h>
>
> #include "QemuFwCfgLibInternal.h"
>
> @@ -94,3 +96,58 @@ InternalQemuFwCfgDmaIsAvailable (
> {
> return FALSE;
> }
> +
> +/**
> +
> + Returns a boolean indicating whether SEV is enabled
> +
> + @retval TRUE SEV is enabled
> + @retval FALSE SEV is disabled
> +**/
> +BOOLEAN
> +InternalQemuFwCfgSevIsEnabled (
> + VOID
> + )
> +{
> + return MemEncryptSevIsEnabled ();
> +}
So, this is not right. We have one instance of MemEncryptSevLib, namely
BaseMemEncryptSevLib. It uses / needs writeable static variables,
therefore it is not usable in SEC phase modules. QemuFwCfgSecLib.inf is
restricted to SEC type client modules, so the above function call would
not work.
Thankfully, this patch won't even compile (showcasing that the edk2
build system works fine). Namely, corresponding to the writeable static
variable requirement in BaseMemEncryptSevLib, we restricted that library
instance to the following client module types:
PEIM DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER UEFI_DRIVER
Whereas, QemuFwCfgSecLib.inf itself is restricted to SEC.
The result is, if you try to build QemuFwCfgSecLib.inf into a SEC
module, the client module type restrictions inherited from
BaseMemEncryptSevLib will cause a build conflict. Otherwise, if you try
to build QemuFwCfgSecLib.inf into, say, a PEIM, then
QemuFwCfgSecLib.inf's own SEC restriction will cause a build conflict.
So this patch cannot compile.
You didn't find this in your testing because OVMF currently has no SEC
phase module that uses fw_cfg -- QemuFwCfgSecLib.inf is never built. You
can manually build it like this, for example (note the "-m" option):
build -a X64 -p OvmfPkg/OvmfPkgX64.dsc -t GCC48 -b DEBUG \
-m OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf
(a) One solution is what I wrote in
<http://mid.mail-archive.com/a07a25d1-0aec-4176-312f-198bf10e29d1@redhat.com>:
> (2) Implement InternalQemuFwCfgSevIsEnabled() in "QemuFwCfgSec.c"
> without using global variables (i.e., with a CPUID on each call, on
> AMD processors, and return constant FALSE on Intel processors).
So basically you should open-code MemEncryptSevIsEnabled() here, without
using any global variables.
(b) Now, a "by the book" solution would be to introduce a SEC instance
of MemEncryptSevLib as well, which would execute CPUID on every
MemEncryptSevIsEnabled() call, and return RETURN_UNSUPPORTED from both
MemEncryptSevClearPageEncMask() and MemEncryptSevSetPageEncMask(),
regardless of architecture (IA32 vs X64). Then this patch would compile
as-is.
(c) But, I don't want to contribute to the proliferation, or growth, of
library instances that are never used in reality. So I dislike both (a)
and (b) above. The only reason we care about QemuFwCfgLib, with regard
to SEV, is because QemuFwCfgLib *sometimes* uses DMA, and SEV has
consequences for DMA.
Notice though that the SEC instance of InternalQemuFwCfgDmaIsAvailable()
returns constant FALSE. This is why it is fine to put ASSERT(FALSE) /
CpuDeadLoop() in the bounce buffer alloc / dealloc routines: they will
never be called.
With the same argument (i.e., we'll never use DMA fw_cfg in SEC), it is
entirely irrelevant for this lib instance whether SEV is present or not.
So I suggest to simply return FALSE from InternalQemuFwCfgSevIsEnabled()
above, and to remark there, in a comment, that
InternalQemuFwCfgDmaIsAvailable() returns constant FALSE, hence SEV
availability is irrelevant.
Thanks,
Laszlo
> +
> +/**
> + Allocate a bounce buffer for SEV DMA.
> +
> + @param[in] NumPage Number of pages.
> + @param[out] Buffer Allocated DMA Buffer pointer
> +
> +**/
> +VOID
> +InternalQemuFwCfgSevDmaAllocateBuffer (
> + IN UINT32 NumPages,
> + OUT VOID **Buffer
> + )
> +{
> + //
> + // We should never reach here
> + //
> + ASSERT (FALSE);
> + CpuDeadLoop ();
> +}
> +
> +/**
> + Free the DMA buffer allocated using InternalQemuFwCfgSevDmaAllocateBuffer
> +
> + @param[in] NumPage Number of pages.
> + @param[in] Buffer DMA Buffer pointer
> +
> +**/
> +VOID
> +InternalQemuFwCfgSevDmaFreeBuffer (
> + IN VOID *Buffer,
> + IN UINT32 NumPages
> + )
> +{
> + //
> + // We should never reach here
> + //
> + ASSERT (FALSE);
> + CpuDeadLoop ();
> +}
>
^ permalink raw reply [flat|nested] 42+ messages in thread
* Re: [RFC v4 09/13] OvmfPkg/QemuFwCfgLib: Implement SEV internal function for SEC phase
2017-05-11 16:24 ` Laszlo Ersek
@ 2017-05-11 18:21 ` Brijesh Singh
0 siblings, 0 replies; 42+ messages in thread
From: Brijesh Singh @ 2017-05-11 18:21 UTC (permalink / raw)
To: Laszlo Ersek, edk2-devel
Cc: brijesh.singh, Thomas.Lendacky, leo.duran, Jordan Justen
On 05/11/2017 11:24 AM, Laszlo Ersek wrote:
> On 05/11/17 00:09, Brijesh Singh wrote:
>> Cc: Jordan Justen <jordan.l.justen@intel.com>
>> Cc: Laszlo Ersek <lersek@redhat.com>
>> Contributed-under: TianoCore Contribution Agreement 1.0
>> Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
>> ---
>> OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf | 1 +
>> OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSec.c | 57 ++++++++++++++++++++
>> 2 files changed, 58 insertions(+)
>>
>> diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf
>> index 7a96575d1851..b782ac6c0aa2 100644
>> --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf
>> +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf
>> @@ -45,4 +45,5 @@ [LibraryClasses]
>> DebugLib
>> IoLib
>> MemoryAllocationLib
>> + MemEncryptSevLib
>
> This will not compile. More below.
>
>>
>> diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSec.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSec.c
>> index 465ccbe90dad..cd04cc814063 100644
>> --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSec.c
>> +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSec.c
>> @@ -6,6 +6,7 @@
>>
>> Copyright (C) 2013, Red Hat, Inc.
>> Copyright (c) 2011 - 2013, Intel Corporation. All rights reserved.<BR>
>> + 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
>> @@ -18,6 +19,7 @@
>>
>> #include <Library/DebugLib.h>
>> #include <Library/QemuFwCfgLib.h>
>> +#include <Library/MemEncryptSevLib.h>
>>
>> #include "QemuFwCfgLibInternal.h"
>>
>> @@ -94,3 +96,58 @@ InternalQemuFwCfgDmaIsAvailable (
>> {
>> return FALSE;
>> }
>> +
>> +/**
>> +
>> + Returns a boolean indicating whether SEV is enabled
>> +
>> + @retval TRUE SEV is enabled
>> + @retval FALSE SEV is disabled
>> +**/
>> +BOOLEAN
>> +InternalQemuFwCfgSevIsEnabled (
>> + VOID
>> + )
>> +{
>> + return MemEncryptSevIsEnabled ();
>> +}
>
> So, this is not right. We have one instance of MemEncryptSevLib, namely
> BaseMemEncryptSevLib. It uses / needs writeable static variables,
> therefore it is not usable in SEC phase modules. QemuFwCfgSecLib.inf is
> restricted to SEC type client modules, so the above function call would
> not work.
>
> Thankfully, this patch won't even compile (showcasing that the edk2
> build system works fine). Namely, corresponding to the writeable static
> variable requirement in BaseMemEncryptSevLib, we restricted that library
> instance to the following client module types:
>
> PEIM DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER UEFI_DRIVER
>
> Whereas, QemuFwCfgSecLib.inf itself is restricted to SEC.
>
> The result is, if you try to build QemuFwCfgSecLib.inf into a SEC
> module, the client module type restrictions inherited from
> BaseMemEncryptSevLib will cause a build conflict. Otherwise, if you try
> to build QemuFwCfgSecLib.inf into, say, a PEIM, then
> QemuFwCfgSecLib.inf's own SEC restriction will cause a build conflict.
>
> So this patch cannot compile.
>
> You didn't find this in your testing because OVMF currently has no SEC
> phase module that uses fw_cfg -- QemuFwCfgSecLib.inf is never built. You
> can manually build it like this, for example (note the "-m" option):
>
> build -a X64 -p OvmfPkg/OvmfPkgX64.dsc -t GCC48 -b DEBUG \
> -m OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf
>
> (a) One solution is what I wrote in
> <http://mid.mail-archive.com/a07a25d1-0aec-4176-312f-198bf10e29d1@redhat.com>:
>
>> (2) Implement InternalQemuFwCfgSevIsEnabled() in "QemuFwCfgSec.c"
>> without using global variables (i.e., with a CPUID on each call, on
>> AMD processors, and return constant FALSE on Intel processors).
>
> So basically you should open-code MemEncryptSevIsEnabled() here, without
> using any global variables.
>
> (b) Now, a "by the book" solution would be to introduce a SEC instance
> of MemEncryptSevLib as well, which would execute CPUID on every
> MemEncryptSevIsEnabled() call, and return RETURN_UNSUPPORTED from both
> MemEncryptSevClearPageEncMask() and MemEncryptSevSetPageEncMask(),
> regardless of architecture (IA32 vs X64). Then this patch would compile
> as-is.
>
> (c) But, I don't want to contribute to the proliferation, or growth, of
> library instances that are never used in reality. So I dislike both (a)
> and (b) above. The only reason we care about QemuFwCfgLib, with regard
> to SEV, is because QemuFwCfgLib *sometimes* uses DMA, and SEV has
> consequences for DMA.
>
> Notice though that the SEC instance of InternalQemuFwCfgDmaIsAvailable()
> returns constant FALSE. This is why it is fine to put ASSERT(FALSE) /
> CpuDeadLoop() in the bounce buffer alloc / dealloc routines: they will
> never be called.
>
> With the same argument (i.e., we'll never use DMA fw_cfg in SEC), it is
> entirely irrelevant for this lib instance whether SEV is present or not.
> So I suggest to simply return FALSE from InternalQemuFwCfgSevIsEnabled()
> above, and to remark there, in a comment, that
> InternalQemuFwCfgDmaIsAvailable() returns constant FALSE, hence SEV
> availability is irrelevant.
>
Agreed, lets not add a code which is never used in reality. I will update the
InternalQemuFwCfgSevIsEnabled() to return FALSE.
-Briejsh
^ permalink raw reply [flat|nested] 42+ messages in thread
* [RFC v4 10/13] OvmfPkg/QemuFwCfgLib: Implement SEV internal functions for PEI phase
2017-05-10 22:09 [RFC v4 00/13] x86: Secure Encrypted Virtualization (AMD) Brijesh Singh
` (8 preceding siblings ...)
2017-05-10 22:09 ` [RFC v4 09/13] OvmfPkg/QemuFwCfgLib: Implement SEV internal function for SEC phase Brijesh Singh
@ 2017-05-10 22:09 ` Brijesh Singh
2017-05-11 16:38 ` Laszlo Ersek
2017-05-10 22:09 ` [RFC v4 11/13] OvmfPkg/QemuFwCfgLib: Implement SEV internal function for Dxe phase Brijesh Singh
` (2 subsequent siblings)
12 siblings, 1 reply; 42+ messages in thread
From: Brijesh Singh @ 2017-05-10 22:09 UTC (permalink / raw)
To: edk2-devel
Cc: Thomas.Lendacky, leo.duran, Brijesh Singh, Jordan Justen,
Laszlo Ersek
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
---
OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf | 1 +
OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c | 72 +++++++++++++++++++-
2 files changed, 71 insertions(+), 2 deletions(-)
diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
index 4f966a85088a..b97b475c7cad 100644
--- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
+++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
@@ -47,4 +47,5 @@ [LibraryClasses]
DebugLib
IoLib
MemoryAllocationLib
+ MemEncryptSevLib
diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c
index ac05f4c347f3..1696512bccaf 100644
--- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c
+++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c
@@ -4,6 +4,7 @@
Copyright (C) 2013, Red Hat, Inc.
Copyright (c) 2011 - 2013, Intel Corporation. All rights reserved.<BR>
+ 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
@@ -14,8 +15,10 @@
WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
+#include <Library/BaseLib.h>
#include <Library/DebugLib.h>
#include <Library/QemuFwCfgLib.h>
+#include <Library/MemEncryptSevLib.h>
#include "QemuFwCfgLibInternal.h"
@@ -76,8 +79,18 @@ QemuFwCfgInitialize (
if ((Revision & FW_CFG_F_DMA) == 0) {
DEBUG ((DEBUG_INFO, "QemuFwCfg interface (IO Port) is supported.\n"));
} else {
- mQemuFwCfgDmaSupported = TRUE;
- DEBUG ((DEBUG_INFO, "QemuFwCfg interface (DMA) is supported.\n"));
+ //
+ // If SEV is enabled then we do not support DMA operations in PEI phase.
+ // This is mainly because DMA in SEV guest requires using bounce buffer
+ // (which need to allocate dynamic memory and allocating a PAGE size'd
+ // buffer can be challenge in PEI phase)
+ //
+ if (InternalQemuFwCfgSevIsEnabled ()) {
+ DEBUG ((DEBUG_INFO, "SEV: QemuFwCfg fallback to IO Port interface.\n"));
+ } else {
+ mQemuFwCfgDmaSupported = TRUE;
+ DEBUG ((DEBUG_INFO, "QemuFwCfg interface (DMA) is supported.\n"));
+ }
}
return RETURN_SUCCESS;
}
@@ -114,3 +127,58 @@ InternalQemuFwCfgDmaIsAvailable (
{
return mQemuFwCfgDmaSupported;
}
+
+/**
+
+ Returns a boolean indicating whether SEV is enabled
+
+ @retval TRUE SEV is enabled
+ @retval FALSE SEV is disabled
+**/
+BOOLEAN
+InternalQemuFwCfgSevIsEnabled (
+ VOID
+ )
+{
+ return MemEncryptSevIsEnabled ();
+}
+
+/**
+ Allocate a bounce buffer for SEV DMA.
+
+ @param[in] NumPage Number of pages.
+ @param[out] Buffer Allocated DMA Buffer pointer
+
+**/
+VOID
+InternalQemuFwCfgSevDmaAllocateBuffer (
+ IN UINT32 NumPages,
+ OUT VOID **Buffer
+ )
+{
+ //
+ // We should never reach here
+ //
+ ASSERT (FALSE);
+ CpuDeadLoop ();
+}
+
+/**
+ Free the DMA buffer allocated using InternalQemuFwCfgSevDmaAllocateBuffer
+
+ @param[in] NumPage Number of pages.
+ @param[in] Buffer DMA Buffer pointer
+
+**/
+VOID
+InternalQemuFwCfgSevDmaFreeBuffer (
+ IN VOID *Buffer,
+ IN UINT32 NumPages
+ )
+{
+ //
+ // We should never reach here
+ //
+ ASSERT (FALSE);
+ CpuDeadLoop ();
+}
--
2.7.4
^ permalink raw reply related [flat|nested] 42+ messages in thread
* Re: [RFC v4 10/13] OvmfPkg/QemuFwCfgLib: Implement SEV internal functions for PEI phase
2017-05-10 22:09 ` [RFC v4 10/13] OvmfPkg/QemuFwCfgLib: Implement SEV internal functions for PEI phase Brijesh Singh
@ 2017-05-11 16:38 ` Laszlo Ersek
0 siblings, 0 replies; 42+ messages in thread
From: Laszlo Ersek @ 2017-05-11 16:38 UTC (permalink / raw)
To: Brijesh Singh, edk2-devel; +Cc: Thomas.Lendacky, leo.duran, Jordan Justen
On 05/11/17 00:09, Brijesh Singh wrote:
> Cc: Jordan Justen <jordan.l.justen@intel.com>
> Cc: Laszlo Ersek <lersek@redhat.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
> ---
> OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf | 1 +
> OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c | 72 +++++++++++++++++++-
> 2 files changed, 71 insertions(+), 2 deletions(-)
Reviewed-by: Laszlo Ersek <lersek@redhat.com>
Thanks,
Laszlo
> diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
> index 4f966a85088a..b97b475c7cad 100644
> --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
> +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
> @@ -47,4 +47,5 @@ [LibraryClasses]
> DebugLib
> IoLib
> MemoryAllocationLib
> + MemEncryptSevLib
>
> diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c
> index ac05f4c347f3..1696512bccaf 100644
> --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c
> +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c
> @@ -4,6 +4,7 @@
>
> Copyright (C) 2013, Red Hat, Inc.
> Copyright (c) 2011 - 2013, Intel Corporation. All rights reserved.<BR>
> + 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
> @@ -14,8 +15,10 @@
> WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
> **/
>
> +#include <Library/BaseLib.h>
> #include <Library/DebugLib.h>
> #include <Library/QemuFwCfgLib.h>
> +#include <Library/MemEncryptSevLib.h>
>
> #include "QemuFwCfgLibInternal.h"
>
> @@ -76,8 +79,18 @@ QemuFwCfgInitialize (
> if ((Revision & FW_CFG_F_DMA) == 0) {
> DEBUG ((DEBUG_INFO, "QemuFwCfg interface (IO Port) is supported.\n"));
> } else {
> - mQemuFwCfgDmaSupported = TRUE;
> - DEBUG ((DEBUG_INFO, "QemuFwCfg interface (DMA) is supported.\n"));
> + //
> + // If SEV is enabled then we do not support DMA operations in PEI phase.
> + // This is mainly because DMA in SEV guest requires using bounce buffer
> + // (which need to allocate dynamic memory and allocating a PAGE size'd
> + // buffer can be challenge in PEI phase)
> + //
> + if (InternalQemuFwCfgSevIsEnabled ()) {
> + DEBUG ((DEBUG_INFO, "SEV: QemuFwCfg fallback to IO Port interface.\n"));
> + } else {
> + mQemuFwCfgDmaSupported = TRUE;
> + DEBUG ((DEBUG_INFO, "QemuFwCfg interface (DMA) is supported.\n"));
> + }
> }
> return RETURN_SUCCESS;
> }
> @@ -114,3 +127,58 @@ InternalQemuFwCfgDmaIsAvailable (
> {
> return mQemuFwCfgDmaSupported;
> }
> +
> +/**
> +
> + Returns a boolean indicating whether SEV is enabled
> +
> + @retval TRUE SEV is enabled
> + @retval FALSE SEV is disabled
> +**/
> +BOOLEAN
> +InternalQemuFwCfgSevIsEnabled (
> + VOID
> + )
> +{
> + return MemEncryptSevIsEnabled ();
> +}
> +
> +/**
> + Allocate a bounce buffer for SEV DMA.
> +
> + @param[in] NumPage Number of pages.
> + @param[out] Buffer Allocated DMA Buffer pointer
> +
> +**/
> +VOID
> +InternalQemuFwCfgSevDmaAllocateBuffer (
> + IN UINT32 NumPages,
> + OUT VOID **Buffer
> + )
> +{
> + //
> + // We should never reach here
> + //
> + ASSERT (FALSE);
> + CpuDeadLoop ();
> +}
> +
> +/**
> + Free the DMA buffer allocated using InternalQemuFwCfgSevDmaAllocateBuffer
> +
> + @param[in] NumPage Number of pages.
> + @param[in] Buffer DMA Buffer pointer
> +
> +**/
> +VOID
> +InternalQemuFwCfgSevDmaFreeBuffer (
> + IN VOID *Buffer,
> + IN UINT32 NumPages
> + )
> +{
> + //
> + // We should never reach here
> + //
> + ASSERT (FALSE);
> + CpuDeadLoop ();
> +}
>
^ permalink raw reply [flat|nested] 42+ messages in thread
* [RFC v4 11/13] OvmfPkg/QemuFwCfgLib: Implement SEV internal function for Dxe phase
2017-05-10 22:09 [RFC v4 00/13] x86: Secure Encrypted Virtualization (AMD) Brijesh Singh
` (9 preceding siblings ...)
2017-05-10 22:09 ` [RFC v4 10/13] OvmfPkg/QemuFwCfgLib: Implement SEV internal functions for PEI phase Brijesh Singh
@ 2017-05-10 22:09 ` Brijesh Singh
2017-05-11 17:07 ` Laszlo Ersek
2017-05-10 22:09 ` [RFC v4 12/13] OvmfPkg/QemuFwCfgLib: Add option to dynamic alloc FW_CFG_DMA Access Brijesh Singh
2017-05-10 22:09 ` [RFC v4 13/13] OvmfPkg/QemuFwCfgLib: Add SEV support Brijesh Singh
12 siblings, 1 reply; 42+ messages in thread
From: Brijesh Singh @ 2017-05-10 22:09 UTC (permalink / raw)
To: edk2-devel
Cc: Thomas.Lendacky, leo.duran, Brijesh Singh, Jordan Justen,
Laszlo Ersek
When SEV is enabled, the DMA must be performed on unencrypted pages.
So when get asked to perfom FWCFG DMA read or write, we allocate a
intermediate (bounce buffer) unencrypted buffer and use this buffer
for DMA read or write.
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
---
OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf | 4 +
OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c | 107 ++++++++++++++++++++
2 files changed, 111 insertions(+)
diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
index 346bb881ffc1..f8df77f788b7 100644
--- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
+++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
@@ -39,6 +39,7 @@ [Sources]
[Packages]
MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
OvmfPkg/OvmfPkg.dec
[LibraryClasses]
@@ -47,4 +48,7 @@ [LibraryClasses]
DebugLib
IoLib
MemoryAllocationLib
+ MemEncryptSevLib
+[Protocols]
+ gEdkiiIoMmuProtocolGuid ## SOMETIMES_CONSUMES
diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c
index ac05f4c347f3..059666ffa99b 100644
--- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c
+++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c
@@ -4,6 +4,7 @@
Copyright (C) 2013, Red Hat, Inc.
Copyright (c) 2011 - 2013, Intel Corporation. All rights reserved.<BR>
+ 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
@@ -14,14 +15,36 @@
WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
+#include "Uefi.h"
+
+#include <Protocol/IoMmu.h>
+
+#include <Library/BaseLib.h>
#include <Library/DebugLib.h>
#include <Library/QemuFwCfgLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/MemEncryptSevLib.h>
#include "QemuFwCfgLibInternal.h"
STATIC BOOLEAN mQemuFwCfgSupported = FALSE;
STATIC BOOLEAN mQemuFwCfgDmaSupported;
+STATIC EDKII_IOMMU_PROTOCOL *mIoMmuProtocol;
+/**
+
+ Returns a boolean indicating whether SEV is enabled
+
+ @retval TRUE SEV is enabled
+ @retval FALSE SEV is disabled
+**/
+BOOLEAN
+InternalQemuFwCfgSevIsEnabled (
+ VOID
+ )
+{
+ return MemEncryptSevIsEnabled ();
+}
/**
Returns a boolean indicating if the firmware configuration interface
@@ -79,6 +102,21 @@ QemuFwCfgInitialize (
mQemuFwCfgDmaSupported = TRUE;
DEBUG ((DEBUG_INFO, "QemuFwCfg interface (DMA) is supported.\n"));
}
+
+ //
+ // When SEV is enabled, the AmdSevDxe driver should have installed the IoMMU
+ // protocol which must be used for mapping host buffer to DMA buffer
+ //
+ if (mQemuFwCfgDmaSupported && MemEncryptSevIsEnabled ()) {
+ EFI_STATUS Status;
+
+ Status = gBS->LocateProtocol (&gEdkiiIoMmuProtocolGuid, NULL, (VOID **)&mIoMmuProtocol);
+ if (EFI_ERROR(Status)) {
+ DEBUG ((DEBUG_WARN, "QemuwCfgSevDma: failed to locate IoMmu protocol, disabling DMA support\n"));
+ mQemuFwCfgDmaSupported = FALSE;
+ }
+ }
+
return RETURN_SUCCESS;
}
@@ -114,3 +152,72 @@ InternalQemuFwCfgDmaIsAvailable (
{
return mQemuFwCfgDmaSupported;
}
+
+/**
+ Allocate a bounce buffer for SEV DMA.
+
+ @param[in] NumPage Number of pages.
+ @param[out] Buffer Allocated DMA Buffer pointer
+
+**/
+VOID
+InternalQemuFwCfgSevDmaAllocateBuffer (
+ IN UINT32 NumPages,
+ OUT VOID **Buffer
+ )
+{
+ EFI_STATUS Status;
+
+ if (!mIoMmuProtocol) {
+ //
+ // We should never reach here
+ //
+ ASSERT (FALSE);
+ CpuDeadLoop ();
+ }
+
+ Status = mIoMmuProtocol->AllocateBuffer (
+ mIoMmuProtocol,
+ 0,
+ EfiBootServicesData,
+ NumPages,
+ Buffer,
+ EDKII_IOMMU_ATTRIBUTE_MEMORY_CACHED
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ DEBUG ((DEBUG_VERBOSE, "QemuFwCfgSevDma allocate buffer 0x%Lx Pages %d\n", (UINTN)Buffer, NumPages));
+
+}
+
+/**
+ Free the DMA buffer allocated using InternalQemuFwCfgSevDmaAllocateBuffer
+
+ @param[in] NumPage Number of pages.
+ @param[in] Buffer DMA Buffer pointer
+
+**/
+VOID
+InternalQemuFwCfgSevDmaFreeBuffer (
+ IN VOID *Buffer,
+ IN UINT32 NumPages
+ )
+{
+ EFI_STATUS Status;
+
+ if (!mIoMmuProtocol) {
+ //
+ // We should never reach here
+ //
+ ASSERT (FALSE);
+ CpuDeadLoop ();
+ }
+
+ Status = mIoMmuProtocol->FreeBuffer (
+ mIoMmuProtocol,
+ NumPages,
+ Buffer
+ );
+ ASSERT_EFI_ERROR (Status);
+ DEBUG ((DEBUG_VERBOSE, "QemuFwCfgSevDma free buffer 0x%Lx Pages %d\n", (UINTN)Buffer, NumPages));
+}
--
2.7.4
^ permalink raw reply related [flat|nested] 42+ messages in thread
* Re: [RFC v4 11/13] OvmfPkg/QemuFwCfgLib: Implement SEV internal function for Dxe phase
2017-05-10 22:09 ` [RFC v4 11/13] OvmfPkg/QemuFwCfgLib: Implement SEV internal function for Dxe phase Brijesh Singh
@ 2017-05-11 17:07 ` Laszlo Ersek
0 siblings, 0 replies; 42+ messages in thread
From: Laszlo Ersek @ 2017-05-11 17:07 UTC (permalink / raw)
To: Brijesh Singh, edk2-devel; +Cc: Thomas.Lendacky, leo.duran, Jordan Justen
comments below:
On 05/11/17 00:09, Brijesh Singh wrote:
> When SEV is enabled, the DMA must be performed on unencrypted pages.
> So when get asked to perfom FWCFG DMA read or write, we allocate a
> intermediate (bounce buffer) unencrypted buffer and use this buffer
> for DMA read or write.
>
>
> Cc: Jordan Justen <jordan.l.justen@intel.com>
> Cc: Laszlo Ersek <lersek@redhat.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
> ---
> OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf | 4 +
> OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c | 107 ++++++++++++++++++++
> 2 files changed, 111 insertions(+)
>
> diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
> index 346bb881ffc1..f8df77f788b7 100644
> --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
> +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
> @@ -39,6 +39,7 @@ [Sources]
>
> [Packages]
> MdePkg/MdePkg.dec
> + MdeModulePkg/MdeModulePkg.dec
> OvmfPkg/OvmfPkg.dec
>
> [LibraryClasses]
> @@ -47,4 +48,7 @@ [LibraryClasses]
> DebugLib
> IoLib
> MemoryAllocationLib
> + MemEncryptSevLib
>
> +[Protocols]
> + gEdkiiIoMmuProtocolGuid ## SOMETIMES_CONSUMES
> diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c
> index ac05f4c347f3..059666ffa99b 100644
> --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c
> +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c
> @@ -4,6 +4,7 @@
>
> Copyright (C) 2013, Red Hat, Inc.
> Copyright (c) 2011 - 2013, Intel Corporation. All rights reserved.<BR>
> + 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
> @@ -14,14 +15,36 @@
> WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
> **/
>
> +#include "Uefi.h"
(1) Not sure what this is needed for, but if it is needed, please use
<Uefi.h>.
> +
> +#include <Protocol/IoMmu.h>
> +
> +#include <Library/BaseLib.h>
> #include <Library/DebugLib.h>
> #include <Library/QemuFwCfgLib.h>
> +#include <Library/UefiBootServicesTableLib.h>
> +#include <Library/MemEncryptSevLib.h>
>
> #include "QemuFwCfgLibInternal.h"
>
> STATIC BOOLEAN mQemuFwCfgSupported = FALSE;
> STATIC BOOLEAN mQemuFwCfgDmaSupported;
>
> +STATIC EDKII_IOMMU_PROTOCOL *mIoMmuProtocol;
> +/**
> +
> + Returns a boolean indicating whether SEV is enabled
> +
> + @retval TRUE SEV is enabled
> + @retval FALSE SEV is disabled
> +**/
> +BOOLEAN
> +InternalQemuFwCfgSevIsEnabled (
> + VOID
> + )
> +{
> + return MemEncryptSevIsEnabled ();
> +}
>
> /**
> Returns a boolean indicating if the firmware configuration interface
> @@ -79,6 +102,21 @@ QemuFwCfgInitialize (
> mQemuFwCfgDmaSupported = TRUE;
> DEBUG ((DEBUG_INFO, "QemuFwCfg interface (DMA) is supported.\n"));
> }
> +
> + //
> + // When SEV is enabled, the AmdSevDxe driver should have installed the IoMMU
> + // protocol which must be used for mapping host buffer to DMA buffer
> + //
(2) The comment should be stronger. Please state that the IOMMU protocol
is guaranteed to be available, because the driver is listed in the
APRIORI DXE file.
> + if (mQemuFwCfgDmaSupported && MemEncryptSevIsEnabled ()) {
> + EFI_STATUS Status;
> +
> + Status = gBS->LocateProtocol (&gEdkiiIoMmuProtocolGuid, NULL, (VOID **)&mIoMmuProtocol);
> + if (EFI_ERROR(Status)) {
(3) Space missing before the paren.
> + DEBUG ((DEBUG_WARN, "QemuwCfgSevDma: failed to locate IoMmu protocol, disabling DMA support\n"));
> + mQemuFwCfgDmaSupported = FALSE;
> + }
> + }
> +
(4) Similarly to (2), this is too permissive. Please use DEBUG_ERROR,
ASSERT (FALSE), and CpuDeadLoop() here.
We must not silently degrade the fw_cfg interface to port-io, because
some client modules equate the presence of some fw_cfg files -- which
can also be found via port-io -- with DMA and fw_cfg write capability.
The expectation of those modules is correct, and we must not break it.
> return RETURN_SUCCESS;
> }
>
> @@ -114,3 +152,72 @@ InternalQemuFwCfgDmaIsAvailable (
> {
> return mQemuFwCfgDmaSupported;
> }
> +
> +/**
> + Allocate a bounce buffer for SEV DMA.
> +
> + @param[in] NumPage Number of pages.
> + @param[out] Buffer Allocated DMA Buffer pointer
> +
> +**/
> +VOID
> +InternalQemuFwCfgSevDmaAllocateBuffer (
> + IN UINT32 NumPages,
> + OUT VOID **Buffer
> + )
> +{
> + EFI_STATUS Status;
> +
> + if (!mIoMmuProtocol) {
> + //
> + // We should never reach here
> + //
> + ASSERT (FALSE);
> + CpuDeadLoop ();
> + }
(5) In turn, this can be replaced with
ASSERT (mIoMmuProtocol != NULL);
> +
> + Status = mIoMmuProtocol->AllocateBuffer (
> + mIoMmuProtocol,
> + 0,
> + EfiBootServicesData,
> + NumPages,
> + Buffer,
> + EDKII_IOMMU_ATTRIBUTE_MEMORY_CACHED
> + );
> + ASSERT_EFI_ERROR (Status);
(6) Please add a CpuDeadLoop() here.
> +
> + DEBUG ((DEBUG_VERBOSE, "QemuFwCfgSevDma allocate buffer 0x%Lx Pages %d\n", (UINTN)Buffer, NumPages));
> +
> +}
(7) Again I suggest to add gEfiCallerBaseName and __FUNCTION__ to the
debug message.
(8) Please also wrap it to 79 chars.
(9) %Lx is not right for printing a UINTN. There is no conversion
specifier that directly matches UINTN, so you'll have to use
(UINT64)(UINTN)Buffer
for portability between IA32 and X64.
(10) NumPages should be printed with %u or %x, it is unsigned.
> +
> +/**
> + Free the DMA buffer allocated using InternalQemuFwCfgSevDmaAllocateBuffer
> +
> + @param[in] NumPage Number of pages.
> + @param[in] Buffer DMA Buffer pointer
> +
> +**/
> +VOID
> +InternalQemuFwCfgSevDmaFreeBuffer (
> + IN VOID *Buffer,
> + IN UINT32 NumPages
> + )
> +{
> + EFI_STATUS Status;
> +
> + if (!mIoMmuProtocol) {
> + //
> + // We should never reach here
> + //
> + ASSERT (FALSE);
> + CpuDeadLoop ();
> + }
> +
> + Status = mIoMmuProtocol->FreeBuffer (
> + mIoMmuProtocol,
> + NumPages,
> + Buffer
> + );
> + ASSERT_EFI_ERROR (Status);
> + DEBUG ((DEBUG_VERBOSE, "QemuFwCfgSevDma free buffer 0x%Lx Pages %d\n", (UINTN)Buffer, NumPages));
> +}
>
The same comments apply here.
Thanks!
Laszlo
^ permalink raw reply [flat|nested] 42+ messages in thread
* [RFC v4 12/13] OvmfPkg/QemuFwCfgLib: Add option to dynamic alloc FW_CFG_DMA Access
2017-05-10 22:09 [RFC v4 00/13] x86: Secure Encrypted Virtualization (AMD) Brijesh Singh
` (10 preceding siblings ...)
2017-05-10 22:09 ` [RFC v4 11/13] OvmfPkg/QemuFwCfgLib: Implement SEV internal function for Dxe phase Brijesh Singh
@ 2017-05-10 22:09 ` Brijesh Singh
2017-05-11 17:10 ` Laszlo Ersek
2017-05-10 22:09 ` [RFC v4 13/13] OvmfPkg/QemuFwCfgLib: Add SEV support Brijesh Singh
12 siblings, 1 reply; 42+ messages in thread
From: Brijesh Singh @ 2017-05-10 22:09 UTC (permalink / raw)
To: edk2-devel; +Cc: Thomas.Lendacky, leo.duran, Brijesh Singh
Update InternalQemuFwCfgDmaBytes() to work with DMA Access pointer.
The change provides the flexibility to dynamically allocate the "Access"
when SEV is enabled.
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
---
OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c | 17 ++++++++++-------
1 file changed, 10 insertions(+), 7 deletions(-)
diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c
index 1bf725d8b7ae..73a19772bee1 100644
--- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c
+++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c
@@ -68,7 +68,8 @@ InternalQemuFwCfgDmaBytes (
IN UINT32 Control
)
{
- volatile FW_CFG_DMA_ACCESS Access;
+ volatile FW_CFG_DMA_ACCESS LocalAccess;
+ volatile FW_CFG_DMA_ACCESS *Access;
UINT32 AccessHigh, AccessLow;
UINT32 Status;
@@ -79,9 +80,11 @@ InternalQemuFwCfgDmaBytes (
return;
}
- Access.Control = SwapBytes32 (Control);
- Access.Length = SwapBytes32 (Size);
- Access.Address = SwapBytes64 ((UINTN)Buffer);
+ Access = &LocalAccess;
+
+ Access->Control = SwapBytes32 (Control);
+ Access->Length = SwapBytes32 (Size);
+ Access->Address = SwapBytes64 ((UINTN)Buffer);
//
// Delimit the transfer from (a) modifications to Access, (b) in case of a
@@ -92,8 +95,8 @@ InternalQemuFwCfgDmaBytes (
//
// Start the transfer.
//
- AccessHigh = (UINT32)RShiftU64 ((UINTN)&Access, 32);
- AccessLow = (UINT32)(UINTN)&Access;
+ AccessHigh = (UINT32)RShiftU64 ((UINTN)Access, 32);
+ AccessLow = (UINT32)(UINTN)Access;
IoWrite32 (FW_CFG_IO_DMA_ADDRESS, SwapBytes32 (AccessHigh));
IoWrite32 (FW_CFG_IO_DMA_ADDRESS + 4, SwapBytes32 (AccessLow));
@@ -106,7 +109,7 @@ InternalQemuFwCfgDmaBytes (
// Wait for the transfer to complete.
//
do {
- Status = SwapBytes32 (Access.Control);
+ Status = SwapBytes32 (Access->Control);
ASSERT ((Status & FW_CFG_DMA_CTL_ERROR) == 0);
} while (Status != 0);
--
2.7.4
^ permalink raw reply related [flat|nested] 42+ messages in thread
* Re: [RFC v4 12/13] OvmfPkg/QemuFwCfgLib: Add option to dynamic alloc FW_CFG_DMA Access
2017-05-10 22:09 ` [RFC v4 12/13] OvmfPkg/QemuFwCfgLib: Add option to dynamic alloc FW_CFG_DMA Access Brijesh Singh
@ 2017-05-11 17:10 ` Laszlo Ersek
0 siblings, 0 replies; 42+ messages in thread
From: Laszlo Ersek @ 2017-05-11 17:10 UTC (permalink / raw)
To: Brijesh Singh, edk2-devel; +Cc: Thomas.Lendacky, leo.duran
On 05/11/17 00:09, Brijesh Singh wrote:
> Update InternalQemuFwCfgDmaBytes() to work with DMA Access pointer.
> The change provides the flexibility to dynamically allocate the "Access"
> when SEV is enabled.
>
>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
> ---
> OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c | 17 ++++++++++-------
> 1 file changed, 10 insertions(+), 7 deletions(-)
Reviewed-by: Laszlo Ersek <lersek@redhat.com>
Thanks,
Laszlo
> diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c
> index 1bf725d8b7ae..73a19772bee1 100644
> --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c
> +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c
> @@ -68,7 +68,8 @@ InternalQemuFwCfgDmaBytes (
> IN UINT32 Control
> )
> {
> - volatile FW_CFG_DMA_ACCESS Access;
> + volatile FW_CFG_DMA_ACCESS LocalAccess;
> + volatile FW_CFG_DMA_ACCESS *Access;
> UINT32 AccessHigh, AccessLow;
> UINT32 Status;
>
> @@ -79,9 +80,11 @@ InternalQemuFwCfgDmaBytes (
> return;
> }
>
> - Access.Control = SwapBytes32 (Control);
> - Access.Length = SwapBytes32 (Size);
> - Access.Address = SwapBytes64 ((UINTN)Buffer);
> + Access = &LocalAccess;
> +
> + Access->Control = SwapBytes32 (Control);
> + Access->Length = SwapBytes32 (Size);
> + Access->Address = SwapBytes64 ((UINTN)Buffer);
>
> //
> // Delimit the transfer from (a) modifications to Access, (b) in case of a
> @@ -92,8 +95,8 @@ InternalQemuFwCfgDmaBytes (
> //
> // Start the transfer.
> //
> - AccessHigh = (UINT32)RShiftU64 ((UINTN)&Access, 32);
> - AccessLow = (UINT32)(UINTN)&Access;
> + AccessHigh = (UINT32)RShiftU64 ((UINTN)Access, 32);
> + AccessLow = (UINT32)(UINTN)Access;
> IoWrite32 (FW_CFG_IO_DMA_ADDRESS, SwapBytes32 (AccessHigh));
> IoWrite32 (FW_CFG_IO_DMA_ADDRESS + 4, SwapBytes32 (AccessLow));
>
> @@ -106,7 +109,7 @@ InternalQemuFwCfgDmaBytes (
> // Wait for the transfer to complete.
> //
> do {
> - Status = SwapBytes32 (Access.Control);
> + Status = SwapBytes32 (Access->Control);
> ASSERT ((Status & FW_CFG_DMA_CTL_ERROR) == 0);
> } while (Status != 0);
>
>
^ permalink raw reply [flat|nested] 42+ messages in thread
* [RFC v4 13/13] OvmfPkg/QemuFwCfgLib: Add SEV support
2017-05-10 22:09 [RFC v4 00/13] x86: Secure Encrypted Virtualization (AMD) Brijesh Singh
` (11 preceding siblings ...)
2017-05-10 22:09 ` [RFC v4 12/13] OvmfPkg/QemuFwCfgLib: Add option to dynamic alloc FW_CFG_DMA Access Brijesh Singh
@ 2017-05-10 22:09 ` Brijesh Singh
2017-05-11 17:44 ` Laszlo Ersek
12 siblings, 1 reply; 42+ messages in thread
From: Brijesh Singh @ 2017-05-10 22:09 UTC (permalink / raw)
To: edk2-devel
Cc: Thomas.Lendacky, leo.duran, Brijesh Singh, Jordan Justen,
Laszlo Ersek
When SEV is enabled, use a bounce buffer to perform the DMA operation.
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
---
OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c | 54 +++++++++++++++++++-
1 file changed, 52 insertions(+), 2 deletions(-)
diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c
index 73a19772bee1..86d8bf880e71 100644
--- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c
+++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c
@@ -72,6 +72,8 @@ InternalQemuFwCfgDmaBytes (
volatile FW_CFG_DMA_ACCESS *Access;
UINT32 AccessHigh, AccessLow;
UINT32 Status;
+ UINT32 NumPages;
+ VOID *DmaBuffer, *BounceBuffer;
ASSERT (Control == FW_CFG_DMA_CTL_WRITE || Control == FW_CFG_DMA_CTL_READ ||
Control == FW_CFG_DMA_CTL_SKIP);
@@ -80,11 +82,44 @@ InternalQemuFwCfgDmaBytes (
return;
}
- Access = &LocalAccess;
+ //
+ // When SEV is enabled then allocate DMA bounce buffer
+ //
+ if (InternalQemuFwCfgSevIsEnabled ()) {
+ UINT32 TotalSize;
+
+ TotalSize = sizeof (*Access);
+ //
+ // Control operation does not need buffer
+ //
+ if (Control != FW_CFG_DMA_CTL_SKIP) {
+ TotalSize += Size;
+ }
+
+ //
+ // Allocate SEV DMA bounce buffer
+ //
+ NumPages = EFI_SIZE_TO_PAGES (TotalSize);
+ InternalQemuFwCfgSevDmaAllocateBuffer (NumPages, &BounceBuffer);
+
+ Access = BounceBuffer;
+ DmaBuffer = BounceBuffer + sizeof (*Access);
+
+ //
+ // Copy data from Host buffer into DMA buffer
+ //
+ if (Buffer && Control == FW_CFG_DMA_CTL_WRITE) {
+ CopyMem (DmaBuffer, Buffer, Size);
+ }
+ } else {
+ Access = &LocalAccess;
+ DmaBuffer = Buffer;
+ BounceBuffer = NULL;
+ }
Access->Control = SwapBytes32 (Control);
Access->Length = SwapBytes32 (Size);
- Access->Address = SwapBytes64 ((UINTN)Buffer);
+ Access->Address = SwapBytes64 ((UINTN)DmaBuffer);
//
// Delimit the transfer from (a) modifications to Access, (b) in case of a
@@ -117,6 +152,21 @@ InternalQemuFwCfgDmaBytes (
// After a read, the caller will want to use Buffer.
//
MemoryFence ();
+
+ //
+ // If Bounce buffer was allocated then copy the data into host buffer and
+ // free the bounce buffer
+ //
+ if (BounceBuffer) {
+ //
+ // Copy data from DMA buffer into host buffer
+ //
+ if (Buffer && Control == FW_CFG_DMA_CTL_READ) {
+ CopyMem (Buffer, DmaBuffer, Size);
+ }
+
+ InternalQemuFwCfgSevDmaFreeBuffer (BounceBuffer, NumPages);
+ }
}
--
2.7.4
^ permalink raw reply related [flat|nested] 42+ messages in thread
* Re: [RFC v4 13/13] OvmfPkg/QemuFwCfgLib: Add SEV support
2017-05-10 22:09 ` [RFC v4 13/13] OvmfPkg/QemuFwCfgLib: Add SEV support Brijesh Singh
@ 2017-05-11 17:44 ` Laszlo Ersek
0 siblings, 0 replies; 42+ messages in thread
From: Laszlo Ersek @ 2017-05-11 17:44 UTC (permalink / raw)
To: Brijesh Singh, edk2-devel; +Cc: Thomas.Lendacky, leo.duran, Jordan Justen
comments below:
On 05/11/17 00:09, Brijesh Singh wrote:
> When SEV is enabled, use a bounce buffer to perform the DMA operation.
>
>
> Cc: Jordan Justen <jordan.l.justen@intel.com>
> Cc: Laszlo Ersek <lersek@redhat.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Brijesh Singh <brijesh.singh@amd.com>
> ---
> OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c | 54 +++++++++++++++++++-
> 1 file changed, 52 insertions(+), 2 deletions(-)
>
> diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c
> index 73a19772bee1..86d8bf880e71 100644
> --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c
> +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLib.c
> @@ -72,6 +72,8 @@ InternalQemuFwCfgDmaBytes (
> volatile FW_CFG_DMA_ACCESS *Access;
> UINT32 AccessHigh, AccessLow;
> UINT32 Status;
> + UINT32 NumPages;
> + VOID *DmaBuffer, *BounceBuffer;
>
> ASSERT (Control == FW_CFG_DMA_CTL_WRITE || Control == FW_CFG_DMA_CTL_READ ||
> Control == FW_CFG_DMA_CTL_SKIP);
> @@ -80,11 +82,44 @@ InternalQemuFwCfgDmaBytes (
> return;
> }
>
> - Access = &LocalAccess;
> + //
> + // When SEV is enabled then allocate DMA bounce buffer
> + //
> + if (InternalQemuFwCfgSevIsEnabled ()) {
> + UINT32 TotalSize;
(1) Please make TotalSize a UINTN.
> +
> + TotalSize = sizeof (*Access);
> + //
> + // Control operation does not need buffer
(2) The comment should say "skip operation".
> + //
> + if (Control != FW_CFG_DMA_CTL_SKIP) {
> + TotalSize += Size;
> + }
> +
> + //
> + // Allocate SEV DMA bounce buffer
> + //
> + NumPages = EFI_SIZE_TO_PAGES (TotalSize);
(3) Please write
NumPages = (UINT32)EFI_SIZE_TO_PAGES (TotalSize)
otherwise Visual Studio will likely yell at us.
> + InternalQemuFwCfgSevDmaAllocateBuffer (NumPages, &BounceBuffer);
> +
> + Access = BounceBuffer;
> + DmaBuffer = BounceBuffer + sizeof (*Access);
(4) Please cast BounceBuffer to (UINT8*) before the addition; we
shouldn't do arithmetic on (VOID*).
> +
> + //
> + // Copy data from Host buffer into DMA buffer
> + //
> + if (Buffer && Control == FW_CFG_DMA_CTL_WRITE) {
(5) The Control check suffices.
If FW_CFG_DMA_CTL_WRITE is passed in, then Buffer can only be NULL if
Size is also 0, and a zero size is handled transparently by CopyMem().
> + CopyMem (DmaBuffer, Buffer, Size);
(Side remark: it's funny how this innocent-looking CopyMem() actually
implements decryption :))
> + }
> + } else {
> + Access = &LocalAccess;
> + DmaBuffer = Buffer;
> + BounceBuffer = NULL;
> + }
>
> Access->Control = SwapBytes32 (Control);
> Access->Length = SwapBytes32 (Size);
> - Access->Address = SwapBytes64 ((UINTN)Buffer);
> + Access->Address = SwapBytes64 ((UINTN)DmaBuffer);
>
> //
> // Delimit the transfer from (a) modifications to Access, (b) in case of a
> @@ -117,6 +152,21 @@ InternalQemuFwCfgDmaBytes (
> // After a read, the caller will want to use Buffer.
> //
> MemoryFence ();
> +
> + //
> + // If Bounce buffer was allocated then copy the data into host buffer and
> + // free the bounce buffer
> + //
> + if (BounceBuffer) {
(6) The edk2 coding style wants us to write this as
if (BounceBuffer != NULL) {
> + //
> + // Copy data from DMA buffer into host buffer
> + //
> + if (Buffer && Control == FW_CFG_DMA_CTL_READ) {
(7) Again, checking only (Control == FW_CFG_DMA_CTL_READ) suffices.
> + CopyMem (Buffer, DmaBuffer, Size);
(Side note: funny how this innocent-looking CopyMem() implements
encryption :))
> + }
> +
> + InternalQemuFwCfgSevDmaFreeBuffer (BounceBuffer, NumPages);
> + }
> }
>
>
>
(8) In several comments above, you wrote "host buffer". Shouldn't those
say "guest buffer"?
I agree it is somewhat confusing, because in DMA parlance, "host buffer"
is likely the right term. Unfortunately, in virtualization, the "device"
that performs the DMA is actually the virtualization host, so "host
buffer" ends up meaning the exact opposite of what we want.
Can you replace the expression "host buffer" with "encrypted guest
buffer" everywhere?
Accordingly, can you replace the word "copy" with "encrypt" vs.
"decrypt" everywhere, as appropriate?
For example, we should end up with something like:
//
// Copy data from Host buffer into DMA buffer
//
-->
//
// Decrypt data from encrypted guest buffer into DMA buffer
//
Otherwise, the logic of the patch looks good to me.
Thanks!
Laszlo
^ permalink raw reply [flat|nested] 42+ messages in thread