Date   

[edk2-staging/RiscV64QemuVirt PATCH V5 01/30] MdePkg/Register: Add register definition header files for RISC-V

Sunil V L
 

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

Add register definitions and access routines for RISC-V. These
headers are leveraged from opensbi repo.

Cc: Daniel Schaefer <git@...>
Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Liming Gao <gaoliming@...>
Cc: Zhiguang Liu <zhiguang.liu@...>
Signed-off-by: Sunil V L <sunilvl@...>
Acked-by: Abner Chang <abner.chang@...>
---
MdePkg/Include/Register/RiscV64/RiscVEncoding.h | 119 ++++++++++++++++++++
MdePkg/Include/Register/RiscV64/RiscVImpl.h | 25 ++++
2 files changed, 144 insertions(+)

diff --git a/MdePkg/Include/Register/RiscV64/RiscVEncoding.h b/MdePkg/Include/Register/RiscV64/RiscVEncoding.h
new file mode 100644
index 000000000000..5c2989b797bf
--- /dev/null
+++ b/MdePkg/Include/Register/RiscV64/RiscVEncoding.h
@@ -0,0 +1,119 @@
+/** @file
+ RISC-V CSR encodings
+
+ Copyright (c) 2019, Western Digital Corporation or its affiliates. All rights reserved.<BR>
+ Copyright (c) 2022, Ventana Micro Systems Inc. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef RISCV_ENCODING_H_
+#define RISCV_ENCODING_H_
+
+#define MSTATUS_SIE 0x00000002UL
+#define MSTATUS_MIE 0x00000008UL
+#define MSTATUS_SPIE_SHIFT 5
+#define MSTATUS_SPIE (1UL << MSTATUS_SPIE_SHIFT)
+#define MSTATUS_UBE 0x00000040UL
+#define MSTATUS_MPIE 0x00000080UL
+#define MSTATUS_SPP_SHIFT 8
+#define MSTATUS_SPP (1UL << MSTATUS_SPP_SHIFT)
+#define MSTATUS_MPP_SHIFT 11
+#define MSTATUS_MPP (3UL << MSTATUS_MPP_SHIFT)
+
+#define SSTATUS_SIE MSTATUS_SIE
+#define SSTATUS_SPIE_SHIFT MSTATUS_SPIE_SHIFT
+#define SSTATUS_SPIE MSTATUS_SPIE
+#define SSTATUS_SPP_SHIFT MSTATUS_SPP_SHIFT
+#define SSTATUS_SPP MSTATUS_SPP
+
+#define IRQ_S_SOFT 1
+#define IRQ_VS_SOFT 2
+#define IRQ_M_SOFT 3
+#define IRQ_S_TIMER 5
+#define IRQ_VS_TIMER 6
+#define IRQ_M_TIMER 7
+#define IRQ_S_EXT 9
+#define IRQ_VS_EXT 10
+#define IRQ_M_EXT 11
+#define IRQ_S_GEXT 12
+#define IRQ_PMU_OVF 13
+
+#define MIP_SSIP (1UL << IRQ_S_SOFT)
+#define MIP_VSSIP (1UL << IRQ_VS_SOFT)
+#define MIP_MSIP (1UL << IRQ_M_SOFT)
+#define MIP_STIP (1UL << IRQ_S_TIMER)
+#define MIP_VSTIP (1UL << IRQ_VS_TIMER)
+#define MIP_MTIP (1UL << IRQ_M_TIMER)
+#define MIP_SEIP (1UL << IRQ_S_EXT)
+#define MIP_VSEIP (1UL << IRQ_VS_EXT)
+#define MIP_MEIP (1UL << IRQ_M_EXT)
+#define MIP_SGEIP (1UL << IRQ_S_GEXT)
+#define MIP_LCOFIP (1UL << IRQ_PMU_OVF)
+
+#define SIP_SSIP MIP_SSIP
+#define SIP_STIP MIP_STIP
+
+#define PRV_U 0UL
+#define PRV_S 1UL
+#define PRV_M 3UL
+
+#define SATP64_MODE 0xF000000000000000ULL
+#define SATP64_ASID 0x0FFFF00000000000ULL
+#define SATP64_PPN 0x00000FFFFFFFFFFFULL
+
+#define SATP_MODE_OFF 0UL
+#define SATP_MODE_SV32 1UL
+#define SATP_MODE_SV39 8UL
+#define SATP_MODE_SV48 9UL
+#define SATP_MODE_SV57 10UL
+#define SATP_MODE_SV64 11UL
+
+#define SATP_MODE SATP64_MODE
+
+/* User Counters/Timers */
+#define CSR_CYCLE 0xc00
+#define CSR_TIME 0xc01
+
+/* Supervisor Trap Setup */
+#define CSR_SSTATUS 0x100
+#define CSR_SEDELEG 0x102
+#define CSR_SIDELEG 0x103
+#define CSR_SIE 0x104
+#define CSR_STVEC 0x105
+
+/* Supervisor Configuration */
+#define CSR_SENVCFG 0x10a
+
+/* Supervisor Trap Handling */
+#define CSR_SSCRATCH 0x140
+#define CSR_SEPC 0x141
+#define CSR_SCAUSE 0x142
+#define CSR_STVAL 0x143
+#define CSR_SIP 0x144
+
+/* Supervisor Protection and Translation */
+#define CSR_SATP 0x180
+
+/* Trap/Exception Causes */
+#define CAUSE_MISALIGNED_FETCH 0x0
+#define CAUSE_FETCH_ACCESS 0x1
+#define CAUSE_ILLEGAL_INSTRUCTION 0x2
+#define CAUSE_BREAKPOINT 0x3
+#define CAUSE_MISALIGNED_LOAD 0x4
+#define CAUSE_LOAD_ACCESS 0x5
+#define CAUSE_MISALIGNED_STORE 0x6
+#define CAUSE_STORE_ACCESS 0x7
+#define CAUSE_USER_ECALL 0x8
+#define CAUSE_SUPERVISOR_ECALL 0x9
+#define CAUSE_VIRTUAL_SUPERVISOR_ECALL 0xa
+#define CAUSE_MACHINE_ECALL 0xb
+#define CAUSE_FETCH_PAGE_FAULT 0xc
+#define CAUSE_LOAD_PAGE_FAULT 0xd
+#define CAUSE_STORE_PAGE_FAULT 0xf
+#define CAUSE_FETCH_GUEST_PAGE_FAULT 0x14
+#define CAUSE_LOAD_GUEST_PAGE_FAULT 0x15
+#define CAUSE_VIRTUAL_INST_FAULT 0x16
+#define CAUSE_STORE_GUEST_PAGE_FAULT 0x17
+
+#endif
diff --git a/MdePkg/Include/Register/RiscV64/RiscVImpl.h b/MdePkg/Include/Register/RiscV64/RiscVImpl.h
new file mode 100644
index 000000000000..ee5c2ba60377
--- /dev/null
+++ b/MdePkg/Include/Register/RiscV64/RiscVImpl.h
@@ -0,0 +1,25 @@
+/** @file
+ RISC-V package definitions.
+
+ Copyright (c) 2016 - 2022, Hewlett Packard Enterprise Development LP. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef RISCV_IMPL_H_
+#define RISCV_IMPL_H_
+
+#include <Register/RiscV64/RiscVEncoding.h>
+
+#define _ASM_FUNC(Name, Section) \
+ .global Name ; \
+ .section #Section, "ax" ; \
+ .type Name, %function ; \
+ .p2align 2 ; \
+ Name:
+
+#define ASM_FUNC(Name) _ASM_FUNC(ASM_PFX(Name), .text. ## Name)
+#define RISCV_TIMER_COMPARE_BITS 32
+
+#endif
--
2.38.0


[edk2-staging/RiscV64QemuVirt PATCH V5 00/30] Add support for RISC-V virt machine

Sunil V L
 

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

Add support for RISC-V qemu virt machine. Most of the changes are migrated from
edk2-platforms repo and followed the latest guidelines for EDK2 code structuring.

The changes at a high level are,

1) MdePkg:
- Add RISC-V register definitions
- Add RISCV_EFI_BOOT_PROTOCOL related definitions
- Add BaseRiscVSbiLib library to make ecall to machine mode firmware

2) UefiCpuPkg:
- Refactor modules/libraries as per latest guidelines
- Add RISC-V support in below modules/libraries.
- CpuTimerLib, CpuExceptionHandlerLib, CpuDxe
- Add new CpuTimerDxe module

3) ArmVirtPkg:
- Migrate below libraries/modules to OvmfPkg
- PlatformBootManagerLib, PlatformHasAcpiDtDxe
- Fix up the consumers of these modules

4) OvmfPkg:
- Refactor the libraries/modules as per latest guidelines
- Add RISC-V support for below libraries/modules.
- Sec, ResetSystemLib, PlatformInitLib, PlatformPei
- Add VirtNorFlashPlatformLib (Copied from ArmVirtPkg and SbsaQemu)
- Add new DSC/FDF files to build for RISC-V virt machine

5) MdeModulePkg/EmbeddedPkg:
- Migrated NvVarStoreFormattedLib from EmbeddedPkg to MdeModulePkg
- Fix up the consumers of NvVarStoreFormattedLib

Changes since V4:
1) Rebased and added ACKs
2) Dropped few patches related to VirtNorFlashDxe since they are already taken care by Ard.

Changes since V3:
1) Addressed Abner's comments
2) Changed folder name from Ia32_X64 to Ia32X64 as per latest guidelines.
2) Rebased

Changes since V2:
1) Fixed issues detected by CI (https://github.com/tianocore/edk2/pull/3471)
2) Added an extra patch to fix up the consumers of NvVarStoreFormattedLib

Changes since V1:
1) Added couple of patches from Ard to optimize the NorFlashDxe in Ovmf.
Note: There will be a separate patch series in future to update existing
consumers of NorFlashDxe driver.
2) Migrated NvVarStoreFormattedLib from EmbeddedPkg to MdeModulePkg
3) Created Null instance of the NorFlashPlatformLib library class
4) Moved NorFlashPlatformLib.h from ArmPlatformPkg

These changes are available at: https://github.com/vlsunil/edk2/tree/RiscV64QemuVirt

Cc: Abner Chang <abner.chang@...>
Cc: Daniel Schaefer <git@...>
Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Liming Gao <gaoliming@...>
Cc: Zhiguang Liu <zhiguang.liu@...>
Cc: Ard Biesheuvel <ardb+tianocore@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Jordan Justen <jordan.l.justen@...>
Cc: Gerd Hoffmann <kraxel@...>
Cc: Rebecca Cran <rebecca@...>
Cc: Peter Grehan <grehan@...>
Cc: Brijesh Singh <brijesh.singh@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: James Bottomley <jejb@...>
Cc: Min Xu <min.m.xu@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Eric Dong <eric.dong@...>
Cc: Ray Ni <ray.ni@...>
Cc: Rahul Kumar <rahul1.kumar@...>
Cc: Leif Lindholm <quic_llindhol@...>
Cc: Sami Mujawar <sami.mujawar@...>
Cc: Andrew Fish <afish@...>
Cc: Jian J Wang <jian.j.wang@...>
Cc: Anup Patel <apatel@...>
Cc: Heinrich Schuchardt <heinrich.schuchardt@...>

Sunil V L (30):
MdePkg/Register: Add register definition header files for RISC-V
MdePkg: Add RISCV_EFI_BOOT_PROTOCOL related definitions
MdePkg/BaseLib: RISC-V: Add few more helper functions
MdePkg: Add BaseRiscVSbiLib Library for RISC-V
OvmfPkg/PlatformInitLib: Refactor to allow other architectures
OvmfPkg/PlatformInitLib: Add support for RISC-V
OvmfPkg/ResetSystemLib: Refactor to allow other architectures.
OvmfPkg/ResetSystemLib: Add support for RISC-V
OvmfPkg/Sec: Refactor to allow other architectures
OvmfPkg/Sec: Add RISC-V support
OvmfPkg/PlatformPei: Refactor to allow other architectures
OvmfPkg/PlatformPei: Add support for RISC-V
UefiCpuPkg/CpuTimerLib: Refactor to allow other architectures
UefiCpuPkg/CpuTimerLib: Add support for RISC-V
UefiCpuPkg/CpuExceptionHandlerLib: Refactor to allow other
architectures
UefiCpuPkg/CpuExceptionHandlerLib: Add support for RISC-V
UefiCpuPkg/CpuDxe: Refactor to allow other architectures
UefiCpuPkg/CpuDxe: Add support for RISC-V
UefiCpuPkg/CpuDxe: Add RISCV_EFI_BOOT_PROTOCOL support
UefiCpuPkg: Add CpuTimerDxe module
ArmVirtPkg/PlatformHasAcpiDtDxe: Move to OvmfPkg
ArmVirtPkg: Fix up the location of PlatformHasAcpiDtDxe
ArmVirtPkg/PlatformBootManagerLib: Move to OvmfPkg
ArmVirtPkg: Fix up the paths to PlatformBootManagerLib
EmbeddedPkg/NvVarStoreFormattedLib: Migrate to MdeModulePkg
ArmVirtPkg: Update the references to NvVarStoreFormattedLib
OvmfPkg: Add VirtNorFlashPlatformLib library
OvmfPkg: RiscVVirt: Add Qemu Virt platform support
Maintainers.txt: Add entry for OvmfPkg/RiscVVirt
UefiCpuPkg/UefiCpuPkg.ci.yaml: Ignore RISC-V file

ArmVirtPkg/ArmVirtPkg.dec | 9 -
EmbeddedPkg/EmbeddedPkg.dec | 3 -
MdeModulePkg/MdeModulePkg.dec | 3 +
MdePkg/MdePkg.dec | 9 +
OvmfPkg/OvmfPkg.dec | 18 +
ArmVirtPkg/ArmVirtCloudHv.dsc | 2 +-
ArmVirtPkg/ArmVirtKvmTool.dsc | 2 +-
ArmVirtPkg/ArmVirtQemu.dsc | 10 +-
ArmVirtPkg/ArmVirtQemuKernel.dsc | 8 +-
MdeModulePkg/MdeModulePkg.dsc | 2 +
MdePkg/MdePkg.dsc | 3 +
OvmfPkg/Platforms/RiscVVirt/RiscVVirt.dsc | 727 ++++++++++++++++++++
UefiCpuPkg/UefiCpuPkg.dsc | 15 +-
OvmfPkg/Platforms/RiscVVirt/RiscVVirt.fdf | 406 +++++++++++
ArmVirtPkg/CloudHvPlatformHasAcpiDtDxe/CloudHvHasAcpiDtDxe.inf | 2 +-
ArmVirtPkg/KvmtoolPlatformDxe/KvmtoolPlatformDxe.inf | 2 +-
{EmbeddedPkg => MdeModulePkg}/Library/NvVarStoreFormattedLib/NvVarStoreFormattedLib.inf | 1 -
MdePkg/Library/BaseLib/BaseLib.inf | 2 +
MdePkg/Library/BaseRiscVSbiLib/BaseRiscVSbiLib.inf | 25 +
{ArmVirtPkg/Library/PlatformBootManagerLib => OvmfPkg/Library/PlatformBootManagerLibVirt}/PlatformBootManagerLib.inf | 3 +-
OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf | 31 +-
OvmfPkg/Library/ResetSystemLib/BaseResetSystemLib.inf | 12 +-
OvmfPkg/Library/ResetSystemLib/BaseResetSystemLibBhyve.inf | 4 +-
OvmfPkg/Library/ResetSystemLib/BaseResetSystemLibMicrovm.inf | 2 +-
OvmfPkg/Library/ResetSystemLib/DxeResetSystemLib.inf | 15 +-
OvmfPkg/Library/ResetSystemLib/DxeResetSystemLibMicrovm.inf | 4 +-
OvmfPkg/Library/VirtNorFlashPlatformLib/VirtNorFlashDeviceTreeLib.inf | 40 ++
OvmfPkg/Library/VirtNorFlashPlatformLib/VirtNorFlashStaticLib.inf | 30 +
{ArmVirtPkg => OvmfPkg}/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.inf | 3 +-
OvmfPkg/PlatformPei/PlatformPei.inf | 43 +-
OvmfPkg/Sec/SecMain.inf | 34 +-
UefiCpuPkg/CpuDxe/CpuDxe.inf | 41 +-
UefiCpuPkg/CpuTimerDxe/CpuTimerDxe.inf | 51 ++
UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf | 21 +-
UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf | 8 +-
UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf | 19 +-
UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf | 8 +-
UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf | 6 +-
UefiCpuPkg/Library/CpuTimerLib/BaseCpuTimerLib.inf | 9 +-
{EmbeddedPkg => MdeModulePkg}/Include/Guid/NvVarStoreFormatted.h | 0
MdePkg/Include/Library/BaseLib.h | 50 ++
MdePkg/Include/Library/BaseRiscVSbiLib.h | 127 ++++
MdePkg/Include/Protocol/RiscVBootProtocol.h | 34 +
MdePkg/Include/Register/RiscV64/RiscVEncoding.h | 119 ++++
MdePkg/Include/Register/RiscV64/RiscVImpl.h | 25 +
OvmfPkg/Include/Library/PlatformInitLib.h | 6 +
{ArmVirtPkg/Library/PlatformBootManagerLib => OvmfPkg/Library/PlatformBootManagerLibVirt}/PlatformBm.h | 0
OvmfPkg/PlatformPei/{ => Ia32X64}/Platform.h | 0
OvmfPkg/PlatformPei/RiscV64/Platform.h | 97 +++
OvmfPkg/Sec/{ => Ia32X64}/AmdSev.h | 0
OvmfPkg/Sec/RiscV64/SecMain.h | 64 ++
OvmfPkg/Sec/SecMainCommon.h | 73 ++
UefiCpuPkg/CpuDxe/{ => Ia32X64}/CpuDxe.h | 0
UefiCpuPkg/CpuDxe/{ => Ia32X64}/CpuGdt.h | 0
UefiCpuPkg/CpuDxe/{ => Ia32X64}/CpuMp.h | 0
UefiCpuPkg/CpuDxe/{ => Ia32X64}/CpuPageTable.h | 0
UefiCpuPkg/CpuDxe/{ => RiscV64}/CpuDxe.h | 122 +---
UefiCpuPkg/CpuTimerDxe/RiscV64/Timer.h | 177 +++++
UefiCpuPkg/Library/CpuExceptionHandlerLib/{ => Ia32X64}/CpuExceptionCommon.h | 0
UefiCpuPkg/Library/CpuExceptionHandlerLib/RiscV64/CpuExceptionHandlerLib.h | 116 ++++
{EmbeddedPkg => MdeModulePkg}/Library/NvVarStoreFormattedLib/NvVarStoreFormattedLib.c | 0
MdePkg/Library/BaseRiscVSbiLib/BaseRiscVSbiLib.c | 227 ++++++
{ArmVirtPkg/Library/PlatformBootManagerLib => OvmfPkg/Library/PlatformBootManagerLibVirt}/PlatformBm.c | 0
{ArmVirtPkg/Library/PlatformBootManagerLib => OvmfPkg/Library/PlatformBootManagerLibVirt}/QemuKernel.c | 0
OvmfPkg/Library/PlatformInitLib/{ => Ia32X64}/Cmos.c | 0
OvmfPkg/Library/PlatformInitLib/{ => Ia32X64}/IntelTdx.c | 0
OvmfPkg/Library/PlatformInitLib/{ => Ia32X64}/IntelTdxNull.c | 0
OvmfPkg/Library/PlatformInitLib/{ => Ia32X64}/MemDetect.c | 0
OvmfPkg/Library/PlatformInitLib/{ => Ia32X64}/Platform.c | 0
OvmfPkg/Library/PlatformInitLib/RiscV64/PlatformPeiLib.c | 72 ++
OvmfPkg/Library/ResetSystemLib/{ => Ia32X64}/BaseResetShutdown.c | 0
OvmfPkg/Library/ResetSystemLib/{ => Ia32X64}/BaseResetShutdownBhyve.c | 0
OvmfPkg/Library/ResetSystemLib/{ => Ia32X64}/DxeResetShutdown.c | 0
OvmfPkg/Library/ResetSystemLib/{ => Ia32X64}/DxeResetSystemLibMicrovm.c | 0
OvmfPkg/Library/ResetSystemLib/{ => Ia32X64}/ResetSystemLib.c | 0
OvmfPkg/Library/ResetSystemLib/{ => Ia32X64}/ResetSystemLibMicrovm.c | 0
OvmfPkg/Library/ResetSystemLib/RiscV64/DxeResetShutdown.c | 20 +
OvmfPkg/Library/ResetSystemLib/RiscV64/ResetSystemLib.c | 128 ++++
OvmfPkg/Library/VirtNorFlashPlatformLib/VirtNorFlashDeviceTreeLib.c | 136 ++++
OvmfPkg/Library/VirtNorFlashPlatformLib/VirtNorFlashStaticLib.c | 40 ++
{ArmVirtPkg => OvmfPkg}/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.c | 0
OvmfPkg/PlatformPei/{ => Ia32X64}/AmdSev.c | 0
OvmfPkg/PlatformPei/{ => Ia32X64}/ClearCache.c | 0
OvmfPkg/PlatformPei/{ => Ia32X64}/FeatureControl.c | 0
OvmfPkg/PlatformPei/{ => Ia32X64}/Fv.c | 0
OvmfPkg/PlatformPei/{ => Ia32X64}/IntelTdx.c | 0
OvmfPkg/PlatformPei/{ => Ia32X64}/MemDetect.c | 0
OvmfPkg/PlatformPei/{ => Ia32X64}/MemTypeInfo.c | 0
OvmfPkg/PlatformPei/{ => Ia32X64}/Platform.c | 0
OvmfPkg/PlatformPei/{ => RiscV64}/Fv.c | 43 +-
OvmfPkg/PlatformPei/RiscV64/MemDetect.c | 212 ++++++
OvmfPkg/PlatformPei/RiscV64/Platform.c | 372 ++++++++++
OvmfPkg/Sec/{ => Ia32X64}/AmdSev.c | 0
OvmfPkg/Sec/{ => Ia32X64}/SecMain.c | 227 +-----
OvmfPkg/Sec/RiscV64/SecMain.c | 573 +++++++++++++++
OvmfPkg/Sec/SecMainCommon.c | 238 +++++++
UefiCpuPkg/CpuDxe/{ => Ia32X64}/CpuDxe.c | 0
UefiCpuPkg/CpuDxe/{ => Ia32X64}/CpuGdt.c | 0
UefiCpuPkg/CpuDxe/{ => Ia32X64}/CpuMp.c | 0
UefiCpuPkg/CpuDxe/{ => Ia32X64}/CpuPageTable.c | 0
UefiCpuPkg/CpuDxe/RiscV64/CpuDxe.c | 365 ++++++++++
UefiCpuPkg/CpuTimerDxe/RiscV64/Timer.c | 294 ++++++++
UefiCpuPkg/Library/CpuExceptionHandlerLib/{ => Ia32X64}/CpuExceptionCommon.c | 0
UefiCpuPkg/Library/CpuExceptionHandlerLib/{ => Ia32X64}/DxeException.c | 0
UefiCpuPkg/Library/CpuExceptionHandlerLib/{ => Ia32X64}/PeiCpuException.c | 0
UefiCpuPkg/Library/CpuExceptionHandlerLib/{ => Ia32X64}/PeiDxeSmmCpuException.c | 0
UefiCpuPkg/Library/CpuExceptionHandlerLib/{ => Ia32X64}/SecPeiCpuException.c | 0
UefiCpuPkg/Library/CpuExceptionHandlerLib/{ => Ia32X64}/SmmException.c | 0
UefiCpuPkg/Library/CpuExceptionHandlerLib/{SmmException.c => RiscV64/CpuExceptionHandlerLib.c} | 83 ++-
UefiCpuPkg/Library/CpuTimerLib/{ => Ia32X64}/BaseCpuTimerLib.c | 0
UefiCpuPkg/Library/CpuTimerLib/{ => Ia32X64}/CpuTimerLib.c | 0
UefiCpuPkg/Library/CpuTimerLib/RiscV64/CpuTimerLib.c | 199 ++++++
ArmVirtPkg/ArmVirtPkg.ci.yaml | 1 -
ArmVirtPkg/ArmVirtQemuFvMain.fdf.inc | 2 +-
Maintainers.txt | 4 +
MdePkg/Library/BaseLib/RiscV64/CpuScratch.S | 31 +
MdePkg/Library/BaseLib/RiscV64/ReadTimer.S | 23 +
MdePkg/Library/BaseLib/RiscV64/RiscVInterrupt.S | 53 +-
OvmfPkg/OvmfPkg.ci.yaml | 1 +
OvmfPkg/Platforms/RiscVVirt/RiscVVirt.fdf.inc | 66 ++
OvmfPkg/Platforms/RiscVVirt/VarStore.fdf.inc | 79 +++
OvmfPkg/Sec/RiscV64/SecEntry.S | 21 +
UefiCpuPkg/CpuTimerDxe/CpuTimer.uni | 14 +
UefiCpuPkg/CpuTimerDxe/CpuTimerExtra.uni | 12 +
UefiCpuPkg/Library/CpuExceptionHandlerLib/RiscV64/SupervisorTrapHandler.S | 105 +++
UefiCpuPkg/UefiCpuPkg.ci.yaml | 1 +
126 files changed, 5758 insertions(+), 527 deletions(-)
create mode 100644 OvmfPkg/Platforms/RiscVVirt/RiscVVirt.dsc
create mode 100644 OvmfPkg/Platforms/RiscVVirt/RiscVVirt.fdf
rename {EmbeddedPkg => MdeModulePkg}/Library/NvVarStoreFormattedLib/NvVarStoreFormattedLib.inf (96%)
create mode 100644 MdePkg/Library/BaseRiscVSbiLib/BaseRiscVSbiLib.inf
rename {ArmVirtPkg/Library/PlatformBootManagerLib => OvmfPkg/Library/PlatformBootManagerLibVirt}/PlatformBootManagerLib.inf (92%)
create mode 100644 OvmfPkg/Library/VirtNorFlashPlatformLib/VirtNorFlashDeviceTreeLib.inf
create mode 100644 OvmfPkg/Library/VirtNorFlashPlatformLib/VirtNorFlashStaticLib.inf
rename {ArmVirtPkg => OvmfPkg}/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.inf (89%)
create mode 100644 UefiCpuPkg/CpuTimerDxe/CpuTimerDxe.inf
rename {EmbeddedPkg => MdeModulePkg}/Include/Guid/NvVarStoreFormatted.h (100%)
create mode 100644 MdePkg/Include/Library/BaseRiscVSbiLib.h
create mode 100644 MdePkg/Include/Protocol/RiscVBootProtocol.h
create mode 100644 MdePkg/Include/Register/RiscV64/RiscVEncoding.h
create mode 100644 MdePkg/Include/Register/RiscV64/RiscVImpl.h
rename {ArmVirtPkg/Library/PlatformBootManagerLib => OvmfPkg/Library/PlatformBootManagerLibVirt}/PlatformBm.h (100%)
rename OvmfPkg/PlatformPei/{ => Ia32X64}/Platform.h (100%)
create mode 100644 OvmfPkg/PlatformPei/RiscV64/Platform.h
rename OvmfPkg/Sec/{ => Ia32X64}/AmdSev.h (100%)
create mode 100644 OvmfPkg/Sec/RiscV64/SecMain.h
create mode 100644 OvmfPkg/Sec/SecMainCommon.h
copy UefiCpuPkg/CpuDxe/{ => Ia32X64}/CpuDxe.h (100%)
rename UefiCpuPkg/CpuDxe/{ => Ia32X64}/CpuGdt.h (100%)
rename UefiCpuPkg/CpuDxe/{ => Ia32X64}/CpuMp.h (100%)
rename UefiCpuPkg/CpuDxe/{ => Ia32X64}/CpuPageTable.h (100%)
rename UefiCpuPkg/CpuDxe/{ => RiscV64}/CpuDxe.h (69%)
create mode 100644 UefiCpuPkg/CpuTimerDxe/RiscV64/Timer.h
rename UefiCpuPkg/Library/CpuExceptionHandlerLib/{ => Ia32X64}/CpuExceptionCommon.h (100%)
create mode 100644 UefiCpuPkg/Library/CpuExceptionHandlerLib/RiscV64/CpuExceptionHandlerLib.h
rename {EmbeddedPkg => MdeModulePkg}/Library/NvVarStoreFormattedLib/NvVarStoreFormattedLib.c (100%)
create mode 100644 MdePkg/Library/BaseRiscVSbiLib/BaseRiscVSbiLib.c
rename {ArmVirtPkg/Library/PlatformBootManagerLib => OvmfPkg/Library/PlatformBootManagerLibVirt}/PlatformBm.c (100%)
rename {ArmVirtPkg/Library/PlatformBootManagerLib => OvmfPkg/Library/PlatformBootManagerLibVirt}/QemuKernel.c (100%)
rename OvmfPkg/Library/PlatformInitLib/{ => Ia32X64}/Cmos.c (100%)
rename OvmfPkg/Library/PlatformInitLib/{ => Ia32X64}/IntelTdx.c (100%)
rename OvmfPkg/Library/PlatformInitLib/{ => Ia32X64}/IntelTdxNull.c (100%)
rename OvmfPkg/Library/PlatformInitLib/{ => Ia32X64}/MemDetect.c (100%)
rename OvmfPkg/Library/PlatformInitLib/{ => Ia32X64}/Platform.c (100%)
create mode 100644 OvmfPkg/Library/PlatformInitLib/RiscV64/PlatformPeiLib.c
rename OvmfPkg/Library/ResetSystemLib/{ => Ia32X64}/BaseResetShutdown.c (100%)
rename OvmfPkg/Library/ResetSystemLib/{ => Ia32X64}/BaseResetShutdownBhyve.c (100%)
rename OvmfPkg/Library/ResetSystemLib/{ => Ia32X64}/DxeResetShutdown.c (100%)
rename OvmfPkg/Library/ResetSystemLib/{ => Ia32X64}/DxeResetSystemLibMicrovm.c (100%)
rename OvmfPkg/Library/ResetSystemLib/{ => Ia32X64}/ResetSystemLib.c (100%)
rename OvmfPkg/Library/ResetSystemLib/{ => Ia32X64}/ResetSystemLibMicrovm.c (100%)
create mode 100644 OvmfPkg/Library/ResetSystemLib/RiscV64/DxeResetShutdown.c
create mode 100644 OvmfPkg/Library/ResetSystemLib/RiscV64/ResetSystemLib.c
create mode 100644 OvmfPkg/Library/VirtNorFlashPlatformLib/VirtNorFlashDeviceTreeLib.c
create mode 100644 OvmfPkg/Library/VirtNorFlashPlatformLib/VirtNorFlashStaticLib.c
rename {ArmVirtPkg => OvmfPkg}/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.c (100%)
rename OvmfPkg/PlatformPei/{ => Ia32X64}/AmdSev.c (100%)
rename OvmfPkg/PlatformPei/{ => Ia32X64}/ClearCache.c (100%)
rename OvmfPkg/PlatformPei/{ => Ia32X64}/FeatureControl.c (100%)
copy OvmfPkg/PlatformPei/{ => Ia32X64}/Fv.c (100%)
rename OvmfPkg/PlatformPei/{ => Ia32X64}/IntelTdx.c (100%)
rename OvmfPkg/PlatformPei/{ => Ia32X64}/MemDetect.c (100%)
rename OvmfPkg/PlatformPei/{ => Ia32X64}/MemTypeInfo.c (100%)
rename OvmfPkg/PlatformPei/{ => Ia32X64}/Platform.c (100%)
rename OvmfPkg/PlatformPei/{ => RiscV64}/Fv.c (63%)
create mode 100644 OvmfPkg/PlatformPei/RiscV64/MemDetect.c
create mode 100644 OvmfPkg/PlatformPei/RiscV64/Platform.c
rename OvmfPkg/Sec/{ => Ia32X64}/AmdSev.c (100%)
rename OvmfPkg/Sec/{ => Ia32X64}/SecMain.c (75%)
create mode 100644 OvmfPkg/Sec/RiscV64/SecMain.c
create mode 100644 OvmfPkg/Sec/SecMainCommon.c
rename UefiCpuPkg/CpuDxe/{ => Ia32X64}/CpuDxe.c (100%)
rename UefiCpuPkg/CpuDxe/{ => Ia32X64}/CpuGdt.c (100%)
rename UefiCpuPkg/CpuDxe/{ => Ia32X64}/CpuMp.c (100%)
rename UefiCpuPkg/CpuDxe/{ => Ia32X64}/CpuPageTable.c (100%)
create mode 100644 UefiCpuPkg/CpuDxe/RiscV64/CpuDxe.c
create mode 100644 UefiCpuPkg/CpuTimerDxe/RiscV64/Timer.c
rename UefiCpuPkg/Library/CpuExceptionHandlerLib/{ => Ia32X64}/CpuExceptionCommon.c (100%)
rename UefiCpuPkg/Library/CpuExceptionHandlerLib/{ => Ia32X64}/DxeException.c (100%)
rename UefiCpuPkg/Library/CpuExceptionHandlerLib/{ => Ia32X64}/PeiCpuException.c (100%)
rename UefiCpuPkg/Library/CpuExceptionHandlerLib/{ => Ia32X64}/PeiDxeSmmCpuException.c (100%)
rename UefiCpuPkg/Library/CpuExceptionHandlerLib/{ => Ia32X64}/SecPeiCpuException.c (100%)
copy UefiCpuPkg/Library/CpuExceptionHandlerLib/{ => Ia32X64}/SmmException.c (100%)
rename UefiCpuPkg/Library/CpuExceptionHandlerLib/{SmmException.c => RiscV64/CpuExceptionHandlerLib.c} (67%)
rename UefiCpuPkg/Library/CpuTimerLib/{ => Ia32X64}/BaseCpuTimerLib.c (100%)
rename UefiCpuPkg/Library/CpuTimerLib/{ => Ia32X64}/CpuTimerLib.c (100%)
create mode 100644 UefiCpuPkg/Library/CpuTimerLib/RiscV64/CpuTimerLib.c
create mode 100644 MdePkg/Library/BaseLib/RiscV64/CpuScratch.S
create mode 100644 MdePkg/Library/BaseLib/RiscV64/ReadTimer.S
create mode 100644 OvmfPkg/Platforms/RiscVVirt/RiscVVirt.fdf.inc
create mode 100644 OvmfPkg/Platforms/RiscVVirt/VarStore.fdf.inc
create mode 100644 OvmfPkg/Sec/RiscV64/SecEntry.S
create mode 100644 UefiCpuPkg/CpuTimerDxe/CpuTimer.uni
create mode 100644 UefiCpuPkg/CpuTimerDxe/CpuTimerExtra.uni
create mode 100644 UefiCpuPkg/Library/CpuExceptionHandlerLib/RiscV64/SupervisorTrapHandler.S

--
2.38.0


Re: [PATCH 1/2] UefiCpuPkg/SmmCpuFeaturesLib: Abstract arch dependent code

Chang, Abner
 

[AMD Official Use Only - General]

Hi Ray,
Ok, the V2 send. Which rename SmmCpuFeaturesLiCommon.c to IntelSmmCpuFeaturesLib.c in the 1/3 patch.

Thanks
Abner

-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Ni, Ray via
groups.io
Sent: Friday, October 28, 2022 5:26 PM
To: devel@edk2.groups.io; Chang, Abner <Abner.Chang@...>
Cc: Attar, AbdulLateef (Abdul Lateef) <AbdulLateef.Attar@...>; Kirkendall,
Garrett <Garrett.Kirkendall@...>; Grimes, Paul <Paul.Grimes@...>;
Dong, Eric <eric.dong@...>; Kumar, Rahul R <rahul.r.kumar@...>
Subject: Re: [edk2-devel] [PATCH 1/2] UefiCpuPkg/SmmCpuFeaturesLib:
Abstract arch dependent code

Caution: This message originated from an External Source. Use proper caution
when opening attachments, clicking links, or responding.


Can you do rename SmmCpuFeaturesLibCommon.c to
IntelSmmCpuFeaturesLib.c?
This helps to keep the change history because I see that almost all content from
Common.c is moved to Intelxxx.c.


-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Chang,
Abner via groups.io
Sent: Friday, September 30, 2022 5:52 PM
To: devel@edk2.groups.io
Cc: Abdul Lateef Attar <abdattar@...>; Garrett Kirkendall
<garrett.kirkendall@...>; Paul Grimes <paul.grimes@...>; Dong,
Eric <eric.dong@...>; Ni, Ray <ray.ni@...>; Kumar, Rahul R
<rahul.r.kumar@...>
Subject: [edk2-devel] [PATCH 1/2] UefiCpuPkg/SmmCpuFeaturesLib:
Abstract arch dependent code

From: Abner Chang <abner.chang@...>

This change strips away Intel X86 implementation and put it in the
IntelSmmCpuFeatureLib

Signed-off-by: Abner Chang <abner.chang@...>
Cc: Abdul Lateef Attar <abdattar@...>
Cc: Garrett Kirkendall <garrett.kirkendall@...>
Cc: Paul Grimes <paul.grimes@...>
Cc: Eric Dong <eric.dong@...>
Cc: Ray Ni <ray.ni@...>
Cc: Rahul Kumar <rahul1.kumar@...>
---
.../SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf | 1 +
.../SmmCpuFeaturesLibStm.inf | 1 +
.../StandaloneMmCpuFeaturesLib.inf | 1 +
.../SmmCpuFeaturesLib/CpuFeaturesLib.h | 6 +
.../IntelSmmCpuFeaturesLib.c | 403 ++++++++++++++++++
.../SmmCpuFeaturesLibCommon.c | 391 +----------------
6 files changed, 413 insertions(+), 390 deletions(-) create mode
100644 UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c

diff --git
a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
index 7b5cef97008..9ac7dde78f8 100644
--- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
+++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
@@ -18,6 +18,7 @@

[Sources]
CpuFeaturesLib.h
+ IntelSmmCpuFeaturesLib.c
SmmCpuFeaturesLib.c
SmmCpuFeaturesLibCommon.c
SmmCpuFeaturesLibNoStm.c
diff --git
a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf
b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf
index 85214ee31cd..86d367e0a09 100644
--- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf
+++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf
@@ -19,6 +19,7 @@

[Sources]
CpuFeaturesLib.h
+ IntelSmmCpuFeaturesLib.c
SmmCpuFeaturesLibCommon.c
SmmStm.c
SmmStm.h
diff --git
a/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.i
nf
b/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.i
nf
index 3eacab48db3..61890205e18 100644
---
a/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.i
nf
+++
b/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.i
nf
@@ -20,6 +20,7 @@

[Sources]
CpuFeaturesLib.h
+ IntelSmmCpuFeaturesLib.c
StandaloneMmCpuFeaturesLib.c
SmmCpuFeaturesLibCommon.c
SmmCpuFeaturesLibNoStm.c
diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/CpuFeaturesLib.h
b/UefiCpuPkg/Library/SmmCpuFeaturesLib/CpuFeaturesLib.h
index 8a1c2adc5c4..fd3e902547c 100644
--- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/CpuFeaturesLib.h
+++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/CpuFeaturesLib.h
@@ -9,6 +9,12 @@
#ifndef CPU_FEATURES_LIB_H_
#define CPU_FEATURES_LIB_H_

+#include <Library/SmmCpuFeaturesLib.h> #include <Library/BaseLib.h>
+#include <Library/PcdLib.h> #include <Library/MemoryAllocationLib.h>
+#include <Library/DebugLib.h>
+
/**
Performs library initialization.

diff --git
a/UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c
b/UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c
new file mode 100644
index 00000000000..cb4897b21e3
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c
@@ -0,0 +1,403 @@
+/** @file
+Implementation shared across all library instances.
+
+Copyright (c) 2010 - 2019, Intel Corporation. All rights
+reserved.<BR> Copyright (c) Microsoft Corporation.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "CpuFeaturesLib.h"
+
+#include <Library/MtrrLib.h>
+#include <Register/Intel/Cpuid.h>
+#include <Register/Intel/SmramSaveStateMap.h>
+
+//
+// Machine Specific Registers (MSRs)
+//
+#define SMM_FEATURES_LIB_IA32_MTRR_CAP 0x0FE
+#define SMM_FEATURES_LIB_IA32_FEATURE_CONTROL 0x03A
+#define SMM_FEATURES_LIB_IA32_SMRR_PHYSBASE 0x1F2
+#define SMM_FEATURES_LIB_IA32_SMRR_PHYSMASK 0x1F3
+#define SMM_FEATURES_LIB_IA32_CORE_SMRR_PHYSBASE 0x0A0 #define
+SMM_FEATURES_LIB_IA32_CORE_SMRR_PHYSMASK 0x0A1
+#define EFI_MSR_SMRR_MASK 0xFFFFF000
+#define EFI_MSR_SMRR_PHYS_MASK_VALID BIT11
+#define SMM_FEATURES_LIB_SMM_FEATURE_CONTROL 0x4E0
+
+//
+// MSRs required for configuration of SMM Code Access Check //
+#define SMM_FEATURES_LIB_IA32_MCA_CAP 0x17D
+#define SMM_CODE_ACCESS_CHK_BIT BIT58
+
+//
+// Set default value to assume IA-32 Architectural MSRs are used //
+UINT32 mSmrrPhysBaseMsr =
SMM_FEATURES_LIB_IA32_SMRR_PHYSBASE;
+UINT32 mSmrrPhysMaskMsr =
SMM_FEATURES_LIB_IA32_SMRR_PHYSMASK;
+
+//
+// Set default value to assume MTRRs need to be configured on each
+SMI // BOOLEAN mNeedConfigureMtrrs = TRUE;
+
+//
+// Array for state of SMRR enable on all CPUs // BOOLEAN
+*mSmrrEnabled;
+
+/**
+ Performs library initialization.
+
+ This initialization function contains common functionality shared
+ betwen all library instance constructors.
+
+**/
+VOID
+CpuFeaturesLibInitialization (
+ VOID
+ )
+{
+ UINT32 RegEax;
+ UINT32 RegEdx;
+ UINTN FamilyId;
+ UINTN ModelId;
+
+ //
+ // Retrieve CPU Family and Model
+ //
+ AsmCpuid (CPUID_VERSION_INFO, &RegEax, NULL, NULL, &RegEdx);
+ FamilyId = (RegEax >> 8) & 0xf; ModelId = (RegEax >> 4) & 0xf; if
+ ((FamilyId == 0x06) || (FamilyId == 0x0f)) {
+ ModelId = ModelId | ((RegEax >> 12) & 0xf0); }
+
+ //
+ // Check CPUID(CPUID_VERSION_INFO).EDX[12] for MTRR capability //
+ if ((RegEdx & BIT12) != 0) {
+ //
+ // Check MTRR_CAP MSR bit 11 for SMRR support
+ //
+ if ((AsmReadMsr64 (SMM_FEATURES_LIB_IA32_MTRR_CAP) & BIT11) !=
0) {
+ ASSERT (FeaturePcdGet (PcdSmrrEnable));
+ }
+ }
+
+ //
+ // Intel(R) 64 and IA-32 Architectures Software Developer's Manual
+ // Volume 3C, Section 35.3 MSRs in the Intel(R) Atom(TM) Processor
Family
+ //
+ // If CPU Family/Model is 06_1CH, 06_26H, 06_27H, 06_35H or 06_36H,
then
+ // SMRR Physical Base and SMM Physical Mask MSRs are not available.
+ //
+ if (FamilyId == 0x06) {
+ if ((ModelId == 0x1C) || (ModelId == 0x26) || (ModelId == 0x27)
+ ||
(ModelId == 0x35) || (ModelId == 0x36)) {
+ ASSERT (!FeaturePcdGet (PcdSmrrEnable));
+ }
+ }
+
+ //
+ // Intel(R) 64 and IA-32 Architectures Software Developer's Manual
+ // Volume 3C, Section 35.2 MSRs in the Intel(R) Core(TM) 2 Processor
Family
+ //
+ // If CPU Family/Model is 06_0F or 06_17, then use Intel(R)
+ Core(TM) 2 // Processor Family MSRs // if (FamilyId == 0x06) {
+ if ((ModelId == 0x17) || (ModelId == 0x0f)) {
+ mSmrrPhysBaseMsr =
SMM_FEATURES_LIB_IA32_CORE_SMRR_PHYSBASE;
+ mSmrrPhysMaskMsr =
SMM_FEATURES_LIB_IA32_CORE_SMRR_PHYSMASK;
+ }
+ }
+
+ //
+ // Intel(R) 64 and IA-32 Architectures Software Developer's Manual
+ // Volume 3C, Section 34.4.2 SMRAM Caching
+ // An IA-32 processor does not automatically write back and invalidate its
+ // caches before entering SMM or before exiting SMM. Because of this
behavior,
+ // care must be taken in the placement of the SMRAM in system memory
and in
+ // the caching of the SMRAM to prevent cache incoherence when
switching back
+ // and forth between SMM and protected mode operation.
+ //
+ // An IA-32 processor is a processor that does not support the
+ Intel 64 // Architecture. Support for the Intel 64 Architecture
+ can be detected
from
+ // CPUID(CPUID_EXTENDED_CPU_SIG).EDX[29]
+ //
+ // If an IA-32 processor is detected, then set mNeedConfigureMtrrs
+ to
TRUE,
+ // so caches are flushed on SMI entry and SMI exit, the interrupted
+ code // MTRRs are saved/restored, and MTRRs for SMM are loaded.
+ //
+ AsmCpuid (CPUID_EXTENDED_FUNCTION, &RegEax, NULL, NULL, NULL); if
+ (RegEax >= CPUID_EXTENDED_CPU_SIG) {
+ AsmCpuid (CPUID_EXTENDED_CPU_SIG, NULL, NULL, NULL, &RegEdx);
+ if ((RegEdx & BIT29) != 0) {
+ mNeedConfigureMtrrs = FALSE;
+ }
+ }
+
+ //
+ // Allocate array for state of SMRR enable on all CPUs //
+ mSmrrEnabled = (BOOLEAN *)AllocatePool (sizeof (BOOLEAN) *
GetCpuMaxLogicalProcessorNumber ());
+ ASSERT (mSmrrEnabled != NULL);
+}
+
+/**
+ Called during the very first SMI into System Management Mode to
+initialize
+ CPU features, including SMBASE, for the currently executing CPU.
+Since
this
+ is the first SMI, the SMRAM Save State Map is at the default
+ address of SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET.
The
currently executing
+ CPU is specified by CpuIndex and CpuIndex can be used to access
information
+ about the currently executing CPU in the ProcessorInfo array and
+ the HotPlugCpuData data structure.
+
+ @param[in] CpuIndex The index of the CPU to initialize. The value
+ must be between 0 and the NumberOfCpus field in
+ the System Management System Table (SMST).
+ @param[in] IsMonarch TRUE if the CpuIndex is the index of the CPU
that
+ was elected as monarch during System Management
+ Mode initialization.
+ FALSE if the CpuIndex is not the index of the CPU
+ that was elected as monarch during System
+ Management Mode initialization.
+ @param[in] ProcessorInfo Pointer to an array of
EFI_PROCESSOR_INFORMATION
+ structures. ProcessorInfo[CpuIndex] contains the
+ information for the currently executing CPU.
+ @param[in] CpuHotPlugData Pointer to the CPU_HOT_PLUG_DATA
structure that
+ contains the ApidId and SmBase arrays.
+**/
+VOID
+EFIAPI
+SmmCpuFeaturesInitializeProcessor (
+ IN UINTN CpuIndex,
+ IN BOOLEAN IsMonarch,
+ IN EFI_PROCESSOR_INFORMATION *ProcessorInfo,
+ IN CPU_HOT_PLUG_DATA *CpuHotPlugData
+ )
+{
+ SMRAM_SAVE_STATE_MAP *CpuState;
+ UINT64 FeatureControl;
+ UINT32 RegEax;
+ UINT32 RegEdx;
+ UINTN FamilyId;
+ UINTN ModelId;
+
+ //
+ // Configure SMBASE.
+ //
+ CpuState = (SMRAM_SAVE_STATE_MAP
*)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
+ CpuState->x86.SMBASE = (UINT32)CpuHotPlugData->SmBase[CpuIndex];
+
+ //
+ // Intel(R) 64 and IA-32 Architectures Software Developer's Manual
+ // Volume 3C, Section 35.2 MSRs in the Intel(R) Core(TM) 2 Processor
Family
+ //
+ // If Intel(R) Core(TM) Core(TM) 2 Processor Family MSRs are being
+ used,
then
+ // make sure SMRR Enable(BIT3) of MSR_FEATURE_CONTROL MSR(0x3A)
is set before
+ // accessing SMRR base/mask MSRs. If Lock(BIT0) of
MSR_FEATURE_CONTROL MSR(0x3A)
+ // is set, then the MSR is locked and can not be modified.
+ //
+ if ((FeaturePcdGet (PcdSmrrEnable)) && (mSmrrPhysBaseMsr ==
SMM_FEATURES_LIB_IA32_CORE_SMRR_PHYSBASE)) {
+ FeatureControl = AsmReadMsr64
(SMM_FEATURES_LIB_IA32_FEATURE_CONTROL);
+ if ((FeatureControl & BIT3) == 0) {
+ ASSERT ((FeatureControl & BIT0) == 0);
+ if ((FeatureControl & BIT0) == 0) {
+ AsmWriteMsr64 (SMM_FEATURES_LIB_IA32_FEATURE_CONTROL,
FeatureControl | BIT3);
+ }
+ }
+ }
+
+ //
+ // If SMRR is supported, then program SMRR base/mask MSRs.
+ // The EFI_MSR_SMRR_PHYS_MASK_VALID bit is not set until the first
normal SMI.
+ // The code that initializes SMM environment is running in normal
+ mode // from SMRAM region. If SMRR is enabled here, then the SMRAM
+ region // is protected and the normal mode code execution will fail.
+ //
+ if (FeaturePcdGet (PcdSmrrEnable)) {
+ //
+ // SMRR size cannot be less than 4-KBytes
+ // SMRR size must be of length 2^n
+ // SMRR base alignment cannot be less than SMRR length
+ //
+ if ((CpuHotPlugData->SmrrSize < SIZE_4KB) ||
+ (CpuHotPlugData->SmrrSize != GetPowerOfTwo32 (CpuHotPlugData-
SmrrSize)) ||
+ ((CpuHotPlugData->SmrrBase & ~(CpuHotPlugData->SmrrSize - 1))
+ !=
CpuHotPlugData->SmrrBase))
+ {
+ //
+ // Print message and halt if CPU is Monarch
+ //
+ if (IsMonarch) {
+ DEBUG ((DEBUG_ERROR, "SMM Base/Size does not meet
alignment/size requirement!\n"));
+ CpuDeadLoop ();
+ }
+ } else {
+ AsmWriteMsr64 (mSmrrPhysBaseMsr, CpuHotPlugData->SmrrBase |
MTRR_CACHE_WRITE_BACK);
+ AsmWriteMsr64 (mSmrrPhysMaskMsr, (~(CpuHotPlugData->SmrrSize -
+ 1)
& EFI_MSR_SMRR_MASK));
+ mSmrrEnabled[CpuIndex] = FALSE;
+ }
+ }
+
+ //
+ // Retrieve CPU Family and Model
+ //
+ AsmCpuid (CPUID_VERSION_INFO, &RegEax, NULL, NULL, &RegEdx);
+ FamilyId = (RegEax >> 8) & 0xf; ModelId = (RegEax >> 4) & 0xf; if
+ ((FamilyId == 0x06) || (FamilyId == 0x0f)) {
+ ModelId = ModelId | ((RegEax >> 12) & 0xf0); }
+
+ //
+ // Intel(R) 64 and IA-32 Architectures Software Developer's Manual
+ // Volume 3C, Section 35.10.1 MSRs in 4th Generation Intel(R)
+ Core(TM) // Processor Family.
+ //
+ // If CPU Family/Model is 06_3C, 06_45, or 06_46 then use 4th
+ Generation // Intel(R) Core(TM) Processor Family MSRs.
+ //
+ if (FamilyId == 0x06) {
+ if ((ModelId == 0x3C) || (ModelId == 0x45) || (ModelId == 0x46) ||
+ (ModelId == 0x3D) || (ModelId == 0x47) || (ModelId == 0x4E)
+ ||
(ModelId == 0x4F) ||
+ (ModelId == 0x3F) || (ModelId == 0x56) || (ModelId == 0x57)
+ ||
(ModelId == 0x5C) ||
+ (ModelId == 0x8C))
+ {
+ //
+ // Check to see if the CPU supports the SMM Code Access Check feature
+ // Do not access this MSR unless the CPU supports the
SmmRegFeatureControl
+ //
+ if ((AsmReadMsr64 (SMM_FEATURES_LIB_IA32_MCA_CAP) &
SMM_CODE_ACCESS_CHK_BIT) != 0) {
+ ASSERT (FeaturePcdGet (PcdSmmFeatureControlEnable));
+ }
+ }
+ }
+
+ //
+ // Call internal worker function that completes the CPU
+initialization
+ //
+ FinishSmmCpuFeaturesInitializeProcessor (); }
+
+/**
+ Determines if MTRR registers must be configured to set SMRAM cache-
ability
+ when executing in System Management Mode.
+
+ @retval TRUE MTRR registers must be configured to set SMRAM cache-
ability.
+ @retval FALSE MTRR registers do not need to be configured to set
SMRAM
+ cache-ability.
+**/
+BOOLEAN
+EFIAPI
+SmmCpuFeaturesNeedConfigureMtrrs (
+ VOID
+ )
+{
+ return mNeedConfigureMtrrs;
+}
+
+/**
+ Disable SMRR register if SMRR is supported and
SmmCpuFeaturesNeedConfigureMtrrs()
+ returns TRUE.
+**/
+VOID
+EFIAPI
+SmmCpuFeaturesDisableSmrr (
+ VOID
+ )
+{
+ if (FeaturePcdGet (PcdSmrrEnable) && mNeedConfigureMtrrs) {
+ AsmWriteMsr64 (mSmrrPhysMaskMsr, AsmReadMsr64
(mSmrrPhysMaskMsr) & ~EFI_MSR_SMRR_PHYS_MASK_VALID);
+ }
+}
+
+/**
+ Enable SMRR register if SMRR is supported and
SmmCpuFeaturesNeedConfigureMtrrs()
+ returns TRUE.
+**/
+VOID
+EFIAPI
+SmmCpuFeaturesReenableSmrr (
+ VOID
+ )
+{
+ if (FeaturePcdGet (PcdSmrrEnable) && mNeedConfigureMtrrs) {
+ AsmWriteMsr64 (mSmrrPhysMaskMsr, AsmReadMsr64
(mSmrrPhysMaskMsr) | EFI_MSR_SMRR_PHYS_MASK_VALID);
+ }
+}
+
+/**
+ Processor specific hook point each time a CPU enters System
+Management
Mode.
+
+ @param[in] CpuIndex The index of the CPU that has entered SMM.
+ The
value
+ must be between 0 and the NumberOfCpus field in the
+ System Management System Table (SMST).
+**/
+VOID
+EFIAPI
+SmmCpuFeaturesRendezvousEntry (
+ IN UINTN CpuIndex
+ )
+{
+ //
+ // If SMRR is supported and this is the first normal SMI, then
+enable SMRR
+ //
+ if (FeaturePcdGet (PcdSmrrEnable) && !mSmrrEnabled[CpuIndex]) {
+ AsmWriteMsr64 (mSmrrPhysMaskMsr, AsmReadMsr64
(mSmrrPhysMaskMsr) | EFI_MSR_SMRR_PHYS_MASK_VALID);
+ mSmrrEnabled[CpuIndex] = TRUE;
+ }
+}
+
+/**
+ Returns the current value of the SMM register for the specified CPU.
+ If the SMM register is not supported, then 0 is returned.
+
+ @param[in] CpuIndex The index of the CPU to read the SMM register.
The
+ value must be between 0 and the NumberOfCpus field in
+ the System Management System Table (SMST).
+ @param[in] RegName Identifies the SMM register to read.
+
+ @return The value of the SMM register specified by RegName from
+ the
CPU
+ specified by CpuIndex.
+**/
+UINT64
+EFIAPI
+SmmCpuFeaturesGetSmmRegister (
+ IN UINTN CpuIndex,
+ IN SMM_REG_NAME RegName
+ )
+{
+ if (FeaturePcdGet (PcdSmmFeatureControlEnable) && (RegName ==
SmmRegFeatureControl)) {
+ return AsmReadMsr64
(SMM_FEATURES_LIB_SMM_FEATURE_CONTROL);
+ }
+
+ return 0;
+}
+
+/**
+ Sets the value of an SMM register on a specified CPU.
+ If the SMM register is not supported, then no action is performed.
+
+ @param[in] CpuIndex The index of the CPU to write the SMM register.
The
+ value must be between 0 and the NumberOfCpus field in
+ the System Management System Table (SMST).
+ @param[in] RegName Identifies the SMM register to write.
+ registers are read-only.
+ @param[in] Value The value to write to the SMM register.
+**/
+VOID
+EFIAPI
+SmmCpuFeaturesSetSmmRegister (
+ IN UINTN CpuIndex,
+ IN SMM_REG_NAME RegName,
+ IN UINT64 Value
+ )
+{
+ if (FeaturePcdGet (PcdSmmFeatureControlEnable) && (RegName ==
SmmRegFeatureControl)) {
+ AsmWriteMsr64 (SMM_FEATURES_LIB_SMM_FEATURE_CONTROL,
Value);
+ }
+}
+
diff --git
a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c
b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c
index 75a0ec8e948..7777e52740e 100644
---
a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c
+++
b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c
@@ -14,278 +14,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
#include <Library/PcdLib.h> #include <Library/MemoryAllocationLib.h>
#include <Library/DebugLib.h> -#include <Register/Intel/Cpuid.h>
-#include <Register/Intel/SmramSaveStateMap.h>
-#include "CpuFeaturesLib.h"
-
-//
-// Machine Specific Registers (MSRs)
-//
-#define SMM_FEATURES_LIB_IA32_MTRR_CAP 0x0FE
-#define SMM_FEATURES_LIB_IA32_FEATURE_CONTROL 0x03A
-#define SMM_FEATURES_LIB_IA32_SMRR_PHYSBASE 0x1F2
-#define SMM_FEATURES_LIB_IA32_SMRR_PHYSMASK 0x1F3
-#define SMM_FEATURES_LIB_IA32_CORE_SMRR_PHYSBASE 0x0A0 -#define
SMM_FEATURES_LIB_IA32_CORE_SMRR_PHYSMASK 0x0A1
-#define EFI_MSR_SMRR_MASK 0xFFFFF000
-#define EFI_MSR_SMRR_PHYS_MASK_VALID BIT11
-#define SMM_FEATURES_LIB_SMM_FEATURE_CONTROL 0x4E0
-
-//
-// MSRs required for configuration of SMM Code Access Check -//
-#define SMM_FEATURES_LIB_IA32_MCA_CAP 0x17D
-#define SMM_CODE_ACCESS_CHK_BIT BIT58
-
-//
-// Set default value to assume IA-32 Architectural MSRs are used -//
-UINT32 mSmrrPhysBaseMsr =
SMM_FEATURES_LIB_IA32_SMRR_PHYSBASE;
-UINT32 mSmrrPhysMaskMsr =
SMM_FEATURES_LIB_IA32_SMRR_PHYSMASK;
-
-//
-// Set default value to assume MTRRs need to be configured on each
SMI -// -BOOLEAN mNeedConfigureMtrrs = TRUE;
-
-//
-// Array for state of SMRR enable on all CPUs -// -BOOLEAN
*mSmrrEnabled;
-
-/**
- Performs library initialization.
-
- This initialization function contains common functionality shared
betwen all
- library instance constructors.
-
-**/
-VOID
-CpuFeaturesLibInitialization (
- VOID
- )
-{
- UINT32 RegEax;
- UINT32 RegEdx;
- UINTN FamilyId;
- UINTN ModelId;
-
- //
- // Retrieve CPU Family and Model
- //
- AsmCpuid (CPUID_VERSION_INFO, &RegEax, NULL, NULL, &RegEdx);
- FamilyId = (RegEax >> 8) & 0xf;
- ModelId = (RegEax >> 4) & 0xf;
- if ((FamilyId == 0x06) || (FamilyId == 0x0f)) {
- ModelId = ModelId | ((RegEax >> 12) & 0xf0);
- }
-
- //
- // Check CPUID(CPUID_VERSION_INFO).EDX[12] for MTRR capability
- //
- if ((RegEdx & BIT12) != 0) {
- //
- // Check MTRR_CAP MSR bit 11 for SMRR support
- //
- if ((AsmReadMsr64 (SMM_FEATURES_LIB_IA32_MTRR_CAP) & BIT11) != 0)
{
- ASSERT (FeaturePcdGet (PcdSmrrEnable));
- }
- }
-
- //
- // Intel(R) 64 and IA-32 Architectures Software Developer's Manual
- // Volume 3C, Section 35.3 MSRs in the Intel(R) Atom(TM) Processor
Family
- //
- // If CPU Family/Model is 06_1CH, 06_26H, 06_27H, 06_35H or 06_36H,
then
- // SMRR Physical Base and SMM Physical Mask MSRs are not available.
- //
- if (FamilyId == 0x06) {
- if ((ModelId == 0x1C) || (ModelId == 0x26) || (ModelId == 0x27) ||
(ModelId == 0x35) || (ModelId == 0x36)) {
- ASSERT (!FeaturePcdGet (PcdSmrrEnable));
- }
- }
-
- //
- // Intel(R) 64 and IA-32 Architectures Software Developer's Manual
- // Volume 3C, Section 35.2 MSRs in the Intel(R) Core(TM) 2
Processor Family
- //
- // If CPU Family/Model is 06_0F or 06_17, then use Intel(R)
Core(TM) 2
- // Processor Family MSRs
- //
- if (FamilyId == 0x06) {
- if ((ModelId == 0x17) || (ModelId == 0x0f)) {
- mSmrrPhysBaseMsr =
SMM_FEATURES_LIB_IA32_CORE_SMRR_PHYSBASE;
- mSmrrPhysMaskMsr =
SMM_FEATURES_LIB_IA32_CORE_SMRR_PHYSMASK;
- }
- }
-
- //
- // Intel(R) 64 and IA-32 Architectures Software Developer's Manual
- // Volume 3C, Section 34.4.2 SMRAM Caching
- // An IA-32 processor does not automatically write back and invalidate its
- // caches before entering SMM or before exiting SMM. Because of this
behavior,
- // care must be taken in the placement of the SMRAM in system memory
and in
- // the caching of the SMRAM to prevent cache incoherence when
switching back
- // and forth between SMM and protected mode operation.
- //
- // An IA-32 processor is a processor that does not support the
Intel 64
- // Architecture. Support for the Intel 64 Architecture can be
detected from
- // CPUID(CPUID_EXTENDED_CPU_SIG).EDX[29]
- //
- // If an IA-32 processor is detected, then set mNeedConfigureMtrrs
to TRUE,
- // so caches are flushed on SMI entry and SMI exit, the interrupted
code
- // MTRRs are saved/restored, and MTRRs for SMM are loaded.
- //
- AsmCpuid (CPUID_EXTENDED_FUNCTION, &RegEax, NULL, NULL, NULL);
- if (RegEax >= CPUID_EXTENDED_CPU_SIG) {
- AsmCpuid (CPUID_EXTENDED_CPU_SIG, NULL, NULL, NULL, &RegEdx);
- if ((RegEdx & BIT29) != 0) {
- mNeedConfigureMtrrs = FALSE;
- }
- }
-
- //
- // Allocate array for state of SMRR enable on all CPUs
- //
- mSmrrEnabled = (BOOLEAN *)AllocatePool (sizeof (BOOLEAN) *
GetCpuMaxLogicalProcessorNumber ());
- ASSERT (mSmrrEnabled != NULL);
-}
-
-/**
- Called during the very first SMI into System Management Mode to
initialize
- CPU features, including SMBASE, for the currently executing CPU.
Since this
- is the first SMI, the SMRAM Save State Map is at the default
address of
- SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET. The
currently
executing
- CPU is specified by CpuIndex and CpuIndex can be used to access
information
- about the currently executing CPU in the ProcessorInfo array and
the
- HotPlugCpuData data structure.
-
- @param[in] CpuIndex The index of the CPU to initialize. The value
- must be between 0 and the NumberOfCpus field in
- the System Management System Table (SMST).
- @param[in] IsMonarch TRUE if the CpuIndex is the index of the CPU
that
- was elected as monarch during System Management
- Mode initialization.
- FALSE if the CpuIndex is not the index of the CPU
- that was elected as monarch during System
- Management Mode initialization.
- @param[in] ProcessorInfo Pointer to an array of
EFI_PROCESSOR_INFORMATION
- structures. ProcessorInfo[CpuIndex] contains the
- information for the currently executing CPU.
- @param[in] CpuHotPlugData Pointer to the CPU_HOT_PLUG_DATA
structure that
- contains the ApidId and SmBase arrays.
-**/
-VOID
-EFIAPI
-SmmCpuFeaturesInitializeProcessor (
- IN UINTN CpuIndex,
- IN BOOLEAN IsMonarch,
- IN EFI_PROCESSOR_INFORMATION *ProcessorInfo,
- IN CPU_HOT_PLUG_DATA *CpuHotPlugData
- )
-{
- SMRAM_SAVE_STATE_MAP *CpuState;
- UINT64 FeatureControl;
- UINT32 RegEax;
- UINT32 RegEdx;
- UINTN FamilyId;
- UINTN ModelId;
-
- //
- // Configure SMBASE.
- //
- CpuState = (SMRAM_SAVE_STATE_MAP
*)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
- CpuState->x86.SMBASE = (UINT32)CpuHotPlugData->SmBase[CpuIndex];
-
- //
- // Intel(R) 64 and IA-32 Architectures Software Developer's Manual
- // Volume 3C, Section 35.2 MSRs in the Intel(R) Core(TM) 2
Processor Family
- //
- // If Intel(R) Core(TM) Core(TM) 2 Processor Family MSRs are being
used, then
- // make sure SMRR Enable(BIT3) of MSR_FEATURE_CONTROL MSR(0x3A) is
set before
- // accessing SMRR base/mask MSRs. If Lock(BIT0) of
MSR_FEATURE_CONTROL MSR(0x3A)
- // is set, then the MSR is locked and can not be modified.
- //
- if ((FeaturePcdGet (PcdSmrrEnable)) && (mSmrrPhysBaseMsr ==
SMM_FEATURES_LIB_IA32_CORE_SMRR_PHYSBASE)) {
- FeatureControl = AsmReadMsr64
(SMM_FEATURES_LIB_IA32_FEATURE_CONTROL);
- if ((FeatureControl & BIT3) == 0) {
- ASSERT ((FeatureControl & BIT0) == 0);
- if ((FeatureControl & BIT0) == 0) {
- AsmWriteMsr64 (SMM_FEATURES_LIB_IA32_FEATURE_CONTROL,
FeatureControl | BIT3);
- }
- }
- }

- //
- // If SMRR is supported, then program SMRR base/mask MSRs.
- // The EFI_MSR_SMRR_PHYS_MASK_VALID bit is not set until the first
normal SMI.
- // The code that initializes SMM environment is running in normal
mode
- // from SMRAM region. If SMRR is enabled here, then the SMRAM
region
- // is protected and the normal mode code execution will fail.
- //
- if (FeaturePcdGet (PcdSmrrEnable)) {
- //
- // SMRR size cannot be less than 4-KBytes
- // SMRR size must be of length 2^n
- // SMRR base alignment cannot be less than SMRR length
- //
- if ((CpuHotPlugData->SmrrSize < SIZE_4KB) ||
- (CpuHotPlugData->SmrrSize != GetPowerOfTwo32 (CpuHotPlugData-
SmrrSize)) ||
- ((CpuHotPlugData->SmrrBase & ~(CpuHotPlugData->SmrrSize - 1)) !=
CpuHotPlugData->SmrrBase))
- {
- //
- // Print message and halt if CPU is Monarch
- //
- if (IsMonarch) {
- DEBUG ((DEBUG_ERROR, "SMM Base/Size does not meet
alignment/size requirement!\n"));
- CpuDeadLoop ();
- }
- } else {
- AsmWriteMsr64 (mSmrrPhysBaseMsr, CpuHotPlugData->SmrrBase |
MTRR_CACHE_WRITE_BACK);
- AsmWriteMsr64 (mSmrrPhysMaskMsr, (~(CpuHotPlugData->SmrrSize - 1)
& EFI_MSR_SMRR_MASK));
- mSmrrEnabled[CpuIndex] = FALSE;
- }
- }
-
- //
- // Retrieve CPU Family and Model
- //
- AsmCpuid (CPUID_VERSION_INFO, &RegEax, NULL, NULL, &RegEdx);
- FamilyId = (RegEax >> 8) & 0xf;
- ModelId = (RegEax >> 4) & 0xf;
- if ((FamilyId == 0x06) || (FamilyId == 0x0f)) {
- ModelId = ModelId | ((RegEax >> 12) & 0xf0);
- }
-
- //
- // Intel(R) 64 and IA-32 Architectures Software Developer's Manual
- // Volume 3C, Section 35.10.1 MSRs in 4th Generation Intel(R)
Core(TM)
- // Processor Family.
- //
- // If CPU Family/Model is 06_3C, 06_45, or 06_46 then use 4th
Generation
- // Intel(R) Core(TM) Processor Family MSRs.
- //
- if (FamilyId == 0x06) {
- if ((ModelId == 0x3C) || (ModelId == 0x45) || (ModelId == 0x46) ||
- (ModelId == 0x3D) || (ModelId == 0x47) || (ModelId == 0x4E) ||
(ModelId == 0x4F) ||
- (ModelId == 0x3F) || (ModelId == 0x56) || (ModelId == 0x57) ||
(ModelId == 0x5C) ||
- (ModelId == 0x8C))
- {
- //
- // Check to see if the CPU supports the SMM Code Access Check feature
- // Do not access this MSR unless the CPU supports the
SmmRegFeatureControl
- //
- if ((AsmReadMsr64 (SMM_FEATURES_LIB_IA32_MCA_CAP) &
SMM_CODE_ACCESS_CHK_BIT) != 0) {
- ASSERT (FeaturePcdGet (PcdSmmFeatureControlEnable));
- }
- }
- }
-
- //
- // Call internal worker function that completes the CPU
initialization
- //
- FinishSmmCpuFeaturesInitializeProcessor (); -}
+#include "CpuFeaturesLib.h"

/**
This function updates the SMRAM save state on the currently
executing CPU @@ -345,75 +75,6 @@
SmmCpuFeaturesSmmRelocationComplete
( { }

-/**
- Determines if MTRR registers must be configured to set SMRAM cache-
ability
- when executing in System Management Mode.
-
- @retval TRUE MTRR registers must be configured to set SMRAM cache-
ability.
- @retval FALSE MTRR registers do not need to be configured to set SMRAM
- cache-ability.
-**/
-BOOLEAN
-EFIAPI
-SmmCpuFeaturesNeedConfigureMtrrs (
- VOID
- )
-{
- return mNeedConfigureMtrrs;
-}
-
-/**
- Disable SMRR register if SMRR is supported and
SmmCpuFeaturesNeedConfigureMtrrs()
- returns TRUE.
-**/
-VOID
-EFIAPI
-SmmCpuFeaturesDisableSmrr (
- VOID
- )
-{
- if (FeaturePcdGet (PcdSmrrEnable) && mNeedConfigureMtrrs) {
- AsmWriteMsr64 (mSmrrPhysMaskMsr, AsmReadMsr64
(mSmrrPhysMaskMsr) & ~EFI_MSR_SMRR_PHYS_MASK_VALID);
- }
-}
-
-/**
- Enable SMRR register if SMRR is supported and
SmmCpuFeaturesNeedConfigureMtrrs()
- returns TRUE.
-**/
-VOID
-EFIAPI
-SmmCpuFeaturesReenableSmrr (
- VOID
- )
-{
- if (FeaturePcdGet (PcdSmrrEnable) && mNeedConfigureMtrrs) {
- AsmWriteMsr64 (mSmrrPhysMaskMsr, AsmReadMsr64
(mSmrrPhysMaskMsr) | EFI_MSR_SMRR_PHYS_MASK_VALID);
- }
-}
-
-/**
- Processor specific hook point each time a CPU enters System
Management Mode.
-
- @param[in] CpuIndex The index of the CPU that has entered SMM.
The value
- must be between 0 and the NumberOfCpus field in the
- System Management System Table (SMST).
-**/
-VOID
-EFIAPI
-SmmCpuFeaturesRendezvousEntry (
- IN UINTN CpuIndex
- )
-{
- //
- // If SMRR is supported and this is the first normal SMI, then
enable SMRR
- //
- if (FeaturePcdGet (PcdSmrrEnable) && !mSmrrEnabled[CpuIndex]) {
- AsmWriteMsr64 (mSmrrPhysMaskMsr, AsmReadMsr64
(mSmrrPhysMaskMsr) | EFI_MSR_SMRR_PHYS_MASK_VALID);
- mSmrrEnabled[CpuIndex] = TRUE;
- }
-}
-
/**
Processor specific hook point each time a CPU exits System
Management Mode.

@@ -456,56 +117,6 @@ SmmCpuFeaturesIsSmmRegisterSupported (
return FALSE;
}

-/**
- Returns the current value of the SMM register for the specified CPU.
- If the SMM register is not supported, then 0 is returned.
-
- @param[in] CpuIndex The index of the CPU to read the SMM register.
The
- value must be between 0 and the NumberOfCpus field in
- the System Management System Table (SMST).
- @param[in] RegName Identifies the SMM register to read.
-
- @return The value of the SMM register specified by RegName from
the CPU
- specified by CpuIndex.
-**/
-UINT64
-EFIAPI
-SmmCpuFeaturesGetSmmRegister (
- IN UINTN CpuIndex,
- IN SMM_REG_NAME RegName
- )
-{
- if (FeaturePcdGet (PcdSmmFeatureControlEnable) && (RegName ==
SmmRegFeatureControl)) {
- return AsmReadMsr64 (SMM_FEATURES_LIB_SMM_FEATURE_CONTROL);
- }
-
- return 0;
-}
-
-/**
- Sets the value of an SMM register on a specified CPU.
- If the SMM register is not supported, then no action is performed.
-
- @param[in] CpuIndex The index of the CPU to write the SMM register.
The
- value must be between 0 and the NumberOfCpus field in
- the System Management System Table (SMST).
- @param[in] RegName Identifies the SMM register to write.
- registers are read-only.
- @param[in] Value The value to write to the SMM register.
-**/
-VOID
-EFIAPI
-SmmCpuFeaturesSetSmmRegister (
- IN UINTN CpuIndex,
- IN SMM_REG_NAME RegName,
- IN UINT64 Value
- )
-{
- if (FeaturePcdGet (PcdSmmFeatureControlEnable) && (RegName ==
SmmRegFeatureControl)) {
- AsmWriteMsr64 (SMM_FEATURES_LIB_SMM_FEATURE_CONTROL,
Value);
- }
-}
-
/**
Read an SMM Save State register on the target processor. If this function
returns EFI_UNSUPPORTED, then the caller is responsible for reading
the
--
2.37.1.windows.1








[PATCH V2 3/3] UefiCpuPkg/SmmCpuFeaturesLib: Clean up header file inclusion in SmmStm.c

Chang, Abner
 

From: Abner Chang <abner.chang@...>

BZ# 4093: Abstract SmmCpuFeaturesLib for sharing common code

Remove the header files those are already included in
CpuFeatureLib.h.

Signed-off-by: Abner Chang <abner.chang@...>
Cc: Abdul Lateef Attar <abdattar@...>
Cc: Garrett Kirkendall <garrett.kirkendall@...>
Cc: Paul Grimes <paul.grimes@...>
Cc: Eric Dong <eric.dong@...>
Cc: Ray Ni <ray.ni@...>
Cc: Rahul Kumar <rahul1.kumar@...>
---
UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmStm.c | 3 ---
1 file changed, 3 deletions(-)

diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmStm.c b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmStm.c
index 4e8f897f5e9..3cf162ada01 100644
--- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmStm.c
+++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmStm.c
@@ -7,11 +7,8 @@
**/

#include <PiMm.h>
-#include <Library/BaseLib.h>
#include <Library/BaseMemoryLib.h>
-#include <Library/MemoryAllocationLib.h>
#include <Library/HobLib.h>
-#include <Library/DebugLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/SmmServicesTableLib.h>
#include <Library/TpmMeasurementLib.h>
--
2.37.1.windows.1


[PATCH V2 2/3] UefiCpuPkg/SmmCpuFeaturesLib: Abstract arch dependent code

Chang, Abner
 

From: Abner Chang <abner.chang@...>

BZ# 4093: Abstract SmmCpuFeaturesLib for sharing common code

This change stripped away the code that can be
shared with other archs or vendors from Intel
implementation and put in to the common file,
leaves the Intel X86 implementation in the
IntelSmmCpuFeatureLib. Also updates the header
file and INF file.

Signed-off-by: Abner Chang <abner.chang@...>
Cc: Abdul Lateef Attar <abdattar@...>
Cc: Garrett Kirkendall <garrett.kirkendall@...>
Cc: Paul Grimes <paul.grimes@...>
Cc: Eric Dong <eric.dong@...>
Cc: Ray Ni <ray.ni@...>
Cc: Rahul Kumar <rahul1.kumar@...>
---
.../SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf | 1 +
.../SmmCpuFeaturesLibStm.inf | 1 +
.../StandaloneMmCpuFeaturesLib.inf | 1 +
.../SmmCpuFeaturesLib/CpuFeaturesLib.h | 6 +
.../IntelSmmCpuFeaturesLib.c | 206 +----------------
.../SmmCpuFeaturesLibCommon.c | 216 ++++++++++++++++++
6 files changed, 227 insertions(+), 204 deletions(-)
create mode 100644 UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c

diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
index 7b5cef97008..9ac7dde78f8 100644
--- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
+++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
@@ -18,6 +18,7 @@

[Sources]
CpuFeaturesLib.h
+ IntelSmmCpuFeaturesLib.c
SmmCpuFeaturesLib.c
SmmCpuFeaturesLibCommon.c
SmmCpuFeaturesLibNoStm.c
diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf
index 85214ee31cd..86d367e0a09 100644
--- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf
+++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf
@@ -19,6 +19,7 @@

[Sources]
CpuFeaturesLib.h
+ IntelSmmCpuFeaturesLib.c
SmmCpuFeaturesLibCommon.c
SmmStm.c
SmmStm.h
diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.inf b/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.inf
index 3eacab48db3..61890205e18 100644
--- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.inf
+++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.inf
@@ -20,6 +20,7 @@

[Sources]
CpuFeaturesLib.h
+ IntelSmmCpuFeaturesLib.c
StandaloneMmCpuFeaturesLib.c
SmmCpuFeaturesLibCommon.c
SmmCpuFeaturesLibNoStm.c
diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/CpuFeaturesLib.h b/UefiCpuPkg/Library/SmmCpuFeaturesLib/CpuFeaturesLib.h
index 8a1c2adc5c4..fd3e902547c 100644
--- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/CpuFeaturesLib.h
+++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/CpuFeaturesLib.h
@@ -9,6 +9,12 @@
#ifndef CPU_FEATURES_LIB_H_
#define CPU_FEATURES_LIB_H_

+#include <Library/SmmCpuFeaturesLib.h>
+#include <Library/BaseLib.h>
+#include <Library/PcdLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/DebugLib.h>
+
/**
Performs library initialization.

diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c b/UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c
index 75a0ec8e948..cb4897b21e3 100644
--- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c
+++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c
@@ -7,16 +7,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent

**/

-#include <PiMm.h>
-#include <Library/SmmCpuFeaturesLib.h>
-#include <Library/BaseLib.h>
+#include "CpuFeaturesLib.h"
+
#include <Library/MtrrLib.h>
-#include <Library/PcdLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/DebugLib.h>
#include <Register/Intel/Cpuid.h>
#include <Register/Intel/SmramSaveStateMap.h>
-#include "CpuFeaturesLib.h"

//
// Machine Specific Registers (MSRs)
@@ -287,64 +282,6 @@ SmmCpuFeaturesInitializeProcessor (
FinishSmmCpuFeaturesInitializeProcessor ();
}

-/**
- This function updates the SMRAM save state on the currently executing CPU
- to resume execution at a specific address after an RSM instruction. This
- function must evaluate the SMRAM save state to determine the execution mode
- the RSM instruction resumes and update the resume execution address with
- either NewInstructionPointer32 or NewInstructionPoint. The auto HALT restart
- flag in the SMRAM save state must always be cleared. This function returns
- the value of the instruction pointer from the SMRAM save state that was
- replaced. If this function returns 0, then the SMRAM save state was not
- modified.
-
- This function is called during the very first SMI on each CPU after
- SmmCpuFeaturesInitializeProcessor() to set a flag in normal execution mode
- to signal that the SMBASE of each CPU has been updated before the default
- SMBASE address is used for the first SMI to the next CPU.
-
- @param[in] CpuIndex The index of the CPU to hook. The value
- must be between 0 and the NumberOfCpus
- field in the System Management System Table
- (SMST).
- @param[in] CpuState Pointer to SMRAM Save State Map for the
- currently executing CPU.
- @param[in] NewInstructionPointer32 Instruction pointer to use if resuming to
- 32-bit execution mode from 64-bit SMM.
- @param[in] NewInstructionPointer Instruction pointer to use if resuming to
- same execution mode as SMM.
-
- @retval 0 This function did modify the SMRAM save state.
- @retval > 0 The original instruction pointer value from the SMRAM save state
- before it was replaced.
-**/
-UINT64
-EFIAPI
-SmmCpuFeaturesHookReturnFromSmm (
- IN UINTN CpuIndex,
- IN SMRAM_SAVE_STATE_MAP *CpuState,
- IN UINT64 NewInstructionPointer32,
- IN UINT64 NewInstructionPointer
- )
-{
- return 0;
-}
-
-/**
- Hook point in normal execution mode that allows the one CPU that was elected
- as monarch during System Management Mode initialization to perform additional
- initialization actions immediately after all of the CPUs have processed their
- first SMI and called SmmCpuFeaturesInitializeProcessor() relocating SMBASE
- into a buffer in SMRAM and called SmmCpuFeaturesHookReturnFromSmm().
-**/
-VOID
-EFIAPI
-SmmCpuFeaturesSmmRelocationComplete (
- VOID
- )
-{
-}
-
/**
Determines if MTRR registers must be configured to set SMRAM cache-ability
when executing in System Management Mode.
@@ -414,48 +351,6 @@ SmmCpuFeaturesRendezvousEntry (
}
}

-/**
- Processor specific hook point each time a CPU exits System Management Mode.
-
- @param[in] CpuIndex The index of the CPU that is exiting SMM. The value must
- be between 0 and the NumberOfCpus field in the System
- Management System Table (SMST).
-**/
-VOID
-EFIAPI
-SmmCpuFeaturesRendezvousExit (
- IN UINTN CpuIndex
- )
-{
-}
-
-/**
- Check to see if an SMM register is supported by a specified CPU.
-
- @param[in] CpuIndex The index of the CPU to check for SMM register support.
- The value must be between 0 and the NumberOfCpus field
- in the System Management System Table (SMST).
- @param[in] RegName Identifies the SMM register to check for support.
-
- @retval TRUE The SMM register specified by RegName is supported by the CPU
- specified by CpuIndex.
- @retval FALSE The SMM register specified by RegName is not supported by the
- CPU specified by CpuIndex.
-**/
-BOOLEAN
-EFIAPI
-SmmCpuFeaturesIsSmmRegisterSupported (
- IN UINTN CpuIndex,
- IN SMM_REG_NAME RegName
- )
-{
- if (FeaturePcdGet (PcdSmmFeatureControlEnable) && (RegName == SmmRegFeatureControl)) {
- return TRUE;
- }
-
- return FALSE;
-}
-
/**
Returns the current value of the SMM register for the specified CPU.
If the SMM register is not supported, then 0 is returned.
@@ -506,100 +401,3 @@ SmmCpuFeaturesSetSmmRegister (
}
}

-/**
- Read an SMM Save State register on the target processor. If this function
- returns EFI_UNSUPPORTED, then the caller is responsible for reading the
- SMM Save Sate register.
-
- @param[in] CpuIndex The index of the CPU to read the SMM Save State. The
- value must be between 0 and the NumberOfCpus field in
- the System Management System Table (SMST).
- @param[in] Register The SMM Save State register to read.
- @param[in] Width The number of bytes to read from the CPU save state.
- @param[out] Buffer Upon return, this holds the CPU register value read
- from the save state.
-
- @retval EFI_SUCCESS The register was read from Save State.
- @retval EFI_INVALID_PARAMETER Buffer is NULL.
- @retval EFI_UNSUPPORTED This function does not support reading Register.
-
-**/
-EFI_STATUS
-EFIAPI
-SmmCpuFeaturesReadSaveStateRegister (
- IN UINTN CpuIndex,
- IN EFI_SMM_SAVE_STATE_REGISTER Register,
- IN UINTN Width,
- OUT VOID *Buffer
- )
-{
- return EFI_UNSUPPORTED;
-}
-
-/**
- Writes an SMM Save State register on the target processor. If this function
- returns EFI_UNSUPPORTED, then the caller is responsible for writing the
- SMM Save Sate register.
-
- @param[in] CpuIndex The index of the CPU to write the SMM Save State. The
- value must be between 0 and the NumberOfCpus field in
- the System Management System Table (SMST).
- @param[in] Register The SMM Save State register to write.
- @param[in] Width The number of bytes to write to the CPU save state.
- @param[in] Buffer Upon entry, this holds the new CPU register value.
-
- @retval EFI_SUCCESS The register was written to Save State.
- @retval EFI_INVALID_PARAMETER Buffer is NULL.
- @retval EFI_UNSUPPORTED This function does not support writing Register.
-**/
-EFI_STATUS
-EFIAPI
-SmmCpuFeaturesWriteSaveStateRegister (
- IN UINTN CpuIndex,
- IN EFI_SMM_SAVE_STATE_REGISTER Register,
- IN UINTN Width,
- IN CONST VOID *Buffer
- )
-{
- return EFI_UNSUPPORTED;
-}
-
-/**
- This function is hook point called after the gEfiSmmReadyToLockProtocolGuid
- notification is completely processed.
-**/
-VOID
-EFIAPI
-SmmCpuFeaturesCompleteSmmReadyToLock (
- VOID
- )
-{
-}
-
-/**
- This API provides a method for a CPU to allocate a specific region for storing page tables.
-
- This API can be called more once to allocate memory for page tables.
-
- Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns a pointer to the
- allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL
- is returned. If there is not enough memory remaining to satisfy the request, then NULL is
- returned.
-
- This function can also return NULL if there is no preference on where the page tables are allocated in SMRAM.
-
- @param Pages The number of 4 KB pages to allocate.
-
- @return A pointer to the allocated buffer for page tables.
- @retval NULL Fail to allocate a specific region for storing page tables,
- Or there is no preference on where the page tables are allocated in SMRAM.
-
-**/
-VOID *
-EFIAPI
-SmmCpuFeaturesAllocatePageTableMemory (
- IN UINTN Pages
- )
-{
- return NULL;
-}
diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c
new file mode 100644
index 00000000000..7777e52740e
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c
@@ -0,0 +1,216 @@
+/** @file
+Implementation shared across all library instances.
+
+Copyright (c) 2010 - 2019, Intel Corporation. All rights reserved.<BR>
+Copyright (c) Microsoft Corporation.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <PiMm.h>
+#include <Library/SmmCpuFeaturesLib.h>
+#include <Library/BaseLib.h>
+#include <Library/MtrrLib.h>
+#include <Library/PcdLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/DebugLib.h>
+
+#include "CpuFeaturesLib.h"
+
+/**
+ This function updates the SMRAM save state on the currently executing CPU
+ to resume execution at a specific address after an RSM instruction. This
+ function must evaluate the SMRAM save state to determine the execution mode
+ the RSM instruction resumes and update the resume execution address with
+ either NewInstructionPointer32 or NewInstructionPoint. The auto HALT restart
+ flag in the SMRAM save state must always be cleared. This function returns
+ the value of the instruction pointer from the SMRAM save state that was
+ replaced. If this function returns 0, then the SMRAM save state was not
+ modified.
+
+ This function is called during the very first SMI on each CPU after
+ SmmCpuFeaturesInitializeProcessor() to set a flag in normal execution mode
+ to signal that the SMBASE of each CPU has been updated before the default
+ SMBASE address is used for the first SMI to the next CPU.
+
+ @param[in] CpuIndex The index of the CPU to hook. The value
+ must be between 0 and the NumberOfCpus
+ field in the System Management System Table
+ (SMST).
+ @param[in] CpuState Pointer to SMRAM Save State Map for the
+ currently executing CPU.
+ @param[in] NewInstructionPointer32 Instruction pointer to use if resuming to
+ 32-bit execution mode from 64-bit SMM.
+ @param[in] NewInstructionPointer Instruction pointer to use if resuming to
+ same execution mode as SMM.
+
+ @retval 0 This function did modify the SMRAM save state.
+ @retval > 0 The original instruction pointer value from the SMRAM save state
+ before it was replaced.
+**/
+UINT64
+EFIAPI
+SmmCpuFeaturesHookReturnFromSmm (
+ IN UINTN CpuIndex,
+ IN SMRAM_SAVE_STATE_MAP *CpuState,
+ IN UINT64 NewInstructionPointer32,
+ IN UINT64 NewInstructionPointer
+ )
+{
+ return 0;
+}
+
+/**
+ Hook point in normal execution mode that allows the one CPU that was elected
+ as monarch during System Management Mode initialization to perform additional
+ initialization actions immediately after all of the CPUs have processed their
+ first SMI and called SmmCpuFeaturesInitializeProcessor() relocating SMBASE
+ into a buffer in SMRAM and called SmmCpuFeaturesHookReturnFromSmm().
+**/
+VOID
+EFIAPI
+SmmCpuFeaturesSmmRelocationComplete (
+ VOID
+ )
+{
+}
+
+/**
+ Processor specific hook point each time a CPU exits System Management Mode.
+
+ @param[in] CpuIndex The index of the CPU that is exiting SMM. The value must
+ be between 0 and the NumberOfCpus field in the System
+ Management System Table (SMST).
+**/
+VOID
+EFIAPI
+SmmCpuFeaturesRendezvousExit (
+ IN UINTN CpuIndex
+ )
+{
+}
+
+/**
+ Check to see if an SMM register is supported by a specified CPU.
+
+ @param[in] CpuIndex The index of the CPU to check for SMM register support.
+ The value must be between 0 and the NumberOfCpus field
+ in the System Management System Table (SMST).
+ @param[in] RegName Identifies the SMM register to check for support.
+
+ @retval TRUE The SMM register specified by RegName is supported by the CPU
+ specified by CpuIndex.
+ @retval FALSE The SMM register specified by RegName is not supported by the
+ CPU specified by CpuIndex.
+**/
+BOOLEAN
+EFIAPI
+SmmCpuFeaturesIsSmmRegisterSupported (
+ IN UINTN CpuIndex,
+ IN SMM_REG_NAME RegName
+ )
+{
+ if (FeaturePcdGet (PcdSmmFeatureControlEnable) && (RegName == SmmRegFeatureControl)) {
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+/**
+ Read an SMM Save State register on the target processor. If this function
+ returns EFI_UNSUPPORTED, then the caller is responsible for reading the
+ SMM Save Sate register.
+
+ @param[in] CpuIndex The index of the CPU to read the SMM Save State. The
+ value must be between 0 and the NumberOfCpus field in
+ the System Management System Table (SMST).
+ @param[in] Register The SMM Save State register to read.
+ @param[in] Width The number of bytes to read from the CPU save state.
+ @param[out] Buffer Upon return, this holds the CPU register value read
+ from the save state.
+
+ @retval EFI_SUCCESS The register was read from Save State.
+ @retval EFI_INVALID_PARAMETER Buffer is NULL.
+ @retval EFI_UNSUPPORTED This function does not support reading Register.
+
+**/
+EFI_STATUS
+EFIAPI
+SmmCpuFeaturesReadSaveStateRegister (
+ IN UINTN CpuIndex,
+ IN EFI_SMM_SAVE_STATE_REGISTER Register,
+ IN UINTN Width,
+ OUT VOID *Buffer
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+/**
+ Writes an SMM Save State register on the target processor. If this function
+ returns EFI_UNSUPPORTED, then the caller is responsible for writing the
+ SMM Save Sate register.
+
+ @param[in] CpuIndex The index of the CPU to write the SMM Save State. The
+ value must be between 0 and the NumberOfCpus field in
+ the System Management System Table (SMST).
+ @param[in] Register The SMM Save State register to write.
+ @param[in] Width The number of bytes to write to the CPU save state.
+ @param[in] Buffer Upon entry, this holds the new CPU register value.
+
+ @retval EFI_SUCCESS The register was written to Save State.
+ @retval EFI_INVALID_PARAMETER Buffer is NULL.
+ @retval EFI_UNSUPPORTED This function does not support writing Register.
+**/
+EFI_STATUS
+EFIAPI
+SmmCpuFeaturesWriteSaveStateRegister (
+ IN UINTN CpuIndex,
+ IN EFI_SMM_SAVE_STATE_REGISTER Register,
+ IN UINTN Width,
+ IN CONST VOID *Buffer
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+/**
+ This function is hook point called after the gEfiSmmReadyToLockProtocolGuid
+ notification is completely processed.
+**/
+VOID
+EFIAPI
+SmmCpuFeaturesCompleteSmmReadyToLock (
+ VOID
+ )
+{
+}
+
+/**
+ This API provides a method for a CPU to allocate a specific region for storing page tables.
+
+ This API can be called more once to allocate memory for page tables.
+
+ Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns a pointer to the
+ allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL
+ is returned. If there is not enough memory remaining to satisfy the request, then NULL is
+ returned.
+
+ This function can also return NULL if there is no preference on where the page tables are allocated in SMRAM.
+
+ @param Pages The number of 4 KB pages to allocate.
+
+ @return A pointer to the allocated buffer for page tables.
+ @retval NULL Fail to allocate a specific region for storing page tables,
+ Or there is no preference on where the page tables are allocated in SMRAM.
+
+**/
+VOID *
+EFIAPI
+SmmCpuFeaturesAllocatePageTableMemory (
+ IN UINTN Pages
+ )
+{
+ return NULL;
+}
--
2.37.1.windows.1


[PATCH V2 1/3] UefiCpuPkg/SmmCpuFeaturesLib: Rename the common C file

Chang, Abner
 

From: Abner Chang <abner.chang@...>

BZ# 4093: Abstract SmmCpuFeaturesLib for sharing common code

Rename SmmCpuFeaturesLiCommon.c to
IntelSmmCpuFeaturesLib, because it was developed
specifically for Intel implementation. The code
that can be shared by other archs or vendors
will be stripped away and put in the common
file in the next patch.

Signed-off-by: Abner Chang <abner.chang@...>
Cc: Abdul Lateef Attar <abdattar@...>
Cc: Garrett Kirkendall <garrett.kirkendall@...>
Cc: Paul Grimes <paul.grimes@...>
Cc: Eric Dong <eric.dong@...>
Cc: Ray Ni <ray.ni@...>
Cc: Rahul Kumar <rahul1.kumar@...>
---
.../{SmmCpuFeaturesLibCommon.c => IntelSmmCpuFeaturesLib.c} | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename UefiCpuPkg/Library/SmmCpuFeaturesLib/{SmmCpuFeaturesLibCommon.c => IntelSmmCpuFeaturesLib.c} (100%)

diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c b/UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c
similarity index 100%
rename from UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c
rename to UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c
--
2.37.1.windows.1


Re: [PATCH EDK2 v1 1/1] ArmPlatformPkg/Drivers/NorFlashDxe:avoid index out of bound

Ard Biesheuvel
 

On Sat, 29 Oct 2022 at 11:29, Wenyi Xie <xiewenyi2@...> wrote:

The size of array BlockMap is 1 in struct FirmwareVolumeHeader, but in
function InitializeFvAndVariableStoreHeaders, BlockMap[1] is been written.
The size of BlockMap[] is not 1. BlockMap is a flexible array declared
in an old fashioned way, and because the type definition is covered by
the spec, we can not change it. Given that this is established idiom,
compilers don't tend to warn about this.

The memory of BlockMap[1] is already allocated, so the code is OK. But
it is better to use a new point to assign this memory.

Cc: Leif Lindholm <quic_llindhol@...>
Cc: Ard Biesheuvel <ardb+tianocore@...>
Signed-off-by: Wenyi Xie <xiewenyi2@...>
Thanks for the patch but this driver is going to be deleted soon so no point.

There is new version of this driver in OvmfPkg/ but given the above, I
don't think there is anything that needs fixing here.

---
ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvb.c | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvb.c b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvb.c
index 0767581308d2..2130e2e76344 100644
--- a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvb.c
+++ b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvb.c
@@ -47,6 +47,7 @@ InitializeFvAndVariableStoreHeaders (
VOID *Headers;
UINTN HeadersLength;
EFI_FIRMWARE_VOLUME_HEADER *FirmwareVolumeHeader;
+ EFI_FV_BLOCK_MAP_ENTRY *BlockMapEntry;
VARIABLE_STORE_HEADER *VariableStoreHeader;
UINT32 NvStorageFtwSpareSize;
UINT32 NvStorageFtwWorkingSize;
@@ -151,10 +152,15 @@ InitializeFvAndVariableStoreHeaders (
FirmwareVolumeHeader->Revision = EFI_FVH_REVISION;
FirmwareVolumeHeader->BlockMap[0].NumBlocks = Instance->Media.LastBlock + 1;
FirmwareVolumeHeader->BlockMap[0].Length = Instance->Media.BlockSize;
- FirmwareVolumeHeader->BlockMap[1].NumBlocks = 0;
- FirmwareVolumeHeader->BlockMap[1].Length = 0;
FirmwareVolumeHeader->Checksum = CalculateCheckSum16 ((UINT16 *)FirmwareVolumeHeader, FirmwareVolumeHeader->HeaderLength);

+ //
+ // EFI_FV_BLOCK_MAP_ENTRY
+ //
+ BlockMapEntry = (EFI_FV_BLOCK_MAP_ENTRY *)((UINTN)Headers + sizeof (EFI_FIRMWARE_VOLUME_HEADER));
+ BlockMapEntry->NumBlocks = 0;
+ BlockMapEntry->Length = 0;
+
//
// VARIABLE_STORE_HEADER
//
--
2.20.1.windows.1


[PATCH RESEND] RedfishPkg/RedfishDiscoverDxe: Fix memory free issue

Chang, Abner
 

From: Abner Chang <abner.chang@...>

Check the memory block pointer before freeing it.

Cc: Nickle Wang <nicklew@...>
Cc: Igor Kulchytskyy <igork@...>
Signed-off-by: Abner Chang <abner.chang@...>
---
.../RedfishDiscoverDxe/RedfishDiscoverDxe.c | 16 ++++++++++------
1 file changed, 10 insertions(+), 6 deletions(-)

diff --git a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c
index 1293ddd633c..1616b5134bc 100644
--- a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c
+++ b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c
@@ -261,6 +261,7 @@ Tcp6GetSubnetInfo (

Tcp6 = (EFI_TCP6_PROTOCOL *)Instance->NetworkInterfaceProtocolInfo.NetworkProtocolInterface;

+ ZeroMem ((VOID *)&IpModedata, sizeof (EFI_IP6_MODE_DATA));
Status = Tcp6->GetModeData (Tcp6, NULL, NULL, &IpModedata, NULL, NULL);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "%a: Can't get IP mode data information\n", __FUNCTION__));
@@ -282,12 +283,15 @@ Tcp6GetSubnetInfo (
}

Instance->SubnetAddrInfoIPv6Number = IpModedata.AddressCount;
- CopyMem (
- (VOID *)Instance->SubnetAddrInfoIPv6,
- (VOID *)&IpModedata.AddressList,
- IpModedata.AddressCount * sizeof (EFI_IP6_ADDRESS_INFO)
- );
- FreePool (IpModedata.AddressList);
+ if (IpModedata.AddressCount != 0 && IpModedata.AddressList != NULL) {
+ CopyMem (
+ (VOID *)Instance->SubnetAddrInfoIPv6,
+ (VOID *)&IpModedata.AddressList,
+ IpModedata.AddressCount * sizeof (EFI_IP6_ADDRESS_INFO)
+ );
+ FreePool(IpModedata.AddressList);
+ }
+
return EFI_SUCCESS;
}

--
2.37.1.windows.1


[PATCH EDK2 v1 0/1] ArmPlatformPkg/Drivers/NorFlashDxe:avoid index out of bound

wenyi,xie
 

Main Changes :
1.Adding new point to assign the value of struct EFI_FV_BLOCK_MAP_ENTRY.

Wenyi Xie (1):
ArmPlatformPkg/Drivers/NorFlashDxe:avoid index out of bound

ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvb.c | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)

--
2.20.1.windows.1


[PATCH EDK2 v1 1/1] ArmPlatformPkg/Drivers/NorFlashDxe:avoid index out of bound

wenyi,xie
 

The size of array BlockMap is 1 in struct FirmwareVolumeHeader, but in
function InitializeFvAndVariableStoreHeaders, BlockMap[1] is been written.
The memory of BlockMap[1] is already allocated, so the code is OK. But
it is better to use a new point to assign this memory.

Cc: Leif Lindholm <quic_llindhol@...>
Cc: Ard Biesheuvel <ardb+tianocore@...>
Signed-off-by: Wenyi Xie <xiewenyi2@...>
---
ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvb.c | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvb.c b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvb.c
index 0767581308d2..2130e2e76344 100644
--- a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvb.c
+++ b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvb.c
@@ -47,6 +47,7 @@ InitializeFvAndVariableStoreHeaders (
VOID *Headers;
UINTN HeadersLength;
EFI_FIRMWARE_VOLUME_HEADER *FirmwareVolumeHeader;
+ EFI_FV_BLOCK_MAP_ENTRY *BlockMapEntry;
VARIABLE_STORE_HEADER *VariableStoreHeader;
UINT32 NvStorageFtwSpareSize;
UINT32 NvStorageFtwWorkingSize;
@@ -151,10 +152,15 @@ InitializeFvAndVariableStoreHeaders (
FirmwareVolumeHeader->Revision = EFI_FVH_REVISION;
FirmwareVolumeHeader->BlockMap[0].NumBlocks = Instance->Media.LastBlock + 1;
FirmwareVolumeHeader->BlockMap[0].Length = Instance->Media.BlockSize;
- FirmwareVolumeHeader->BlockMap[1].NumBlocks = 0;
- FirmwareVolumeHeader->BlockMap[1].Length = 0;
FirmwareVolumeHeader->Checksum = CalculateCheckSum16 ((UINT16 *)FirmwareVolumeHeader, FirmwareVolumeHeader->HeaderLength);

+ //
+ // EFI_FV_BLOCK_MAP_ENTRY
+ //
+ BlockMapEntry = (EFI_FV_BLOCK_MAP_ENTRY *)((UINTN)Headers + sizeof (EFI_FIRMWARE_VOLUME_HEADER));
+ BlockMapEntry->NumBlocks = 0;
+ BlockMapEntry->Length = 0;
+
//
// VARIABLE_STORE_HEADER
//
--
2.20.1.windows.1


Re: [PATCH] RedfishPkg/RedfishDiscoverDxe: Fix memory free issue

Nickle Wang
 


Reviewed-by: Nickle Wang <nicklew@...>


From: devel@edk2.groups.io <devel@edk2.groups.io> on behalf of Chang, Abner via groups.io <abner.chang@...>
Sent: Saturday, October 29, 2022 11:59 AM
To: devel@edk2.groups.io <devel@edk2.groups.io>
Cc: Nickle Wang <nickle@...>; Igor Kulchytskyy <igork@...>
Subject: [edk2-devel] [PATCH] RedfishPkg/RedfishDiscoverDxe: Fix memory free issue
 
External email: Use caution opening links or attachments


From: Abner Chang <abner.chang@...>

Check the memory block pointer before freeing it.

Cc: Nickle Wang <nickle@...>
Cc: Igor Kulchytskyy <igork@...>
Signed-off-by: Abner Chang <abner.chang@...>
---
 .../RedfishDiscoverDxe/RedfishDiscoverDxe.c      | 16 ++++++++++------
 1 file changed, 10 insertions(+), 6 deletions(-)

diff --git a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c
index 1293ddd633c..1616b5134bc 100644
--- a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c
+++ b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c
@@ -261,6 +261,7 @@ Tcp6GetSubnetInfo (

   Tcp6 = (EFI_TCP6_PROTOCOL *)Instance->NetworkInterfaceProtocolInfo.NetworkProtocolInterface;

+  ZeroMem ((VOID *)&IpModedata, sizeof (EFI_IP6_MODE_DATA));
   Status = Tcp6->GetModeData (Tcp6, NULL, NULL, &IpModedata, NULL, NULL);
   if (EFI_ERROR (Status)) {
     DEBUG ((DEBUG_ERROR, "%a: Can't get IP mode data information\n", __FUNCTION__));
@@ -282,12 +283,15 @@ Tcp6GetSubnetInfo (
   }

   Instance->SubnetAddrInfoIPv6Number = IpModedata.AddressCount;
-  CopyMem (
-    (VOID *)Instance->SubnetAddrInfoIPv6,
-    (VOID *)&IpModedata.AddressList,
-    IpModedata.AddressCount * sizeof (EFI_IP6_ADDRESS_INFO)
-    );
-  FreePool (IpModedata.AddressList);
+  if (IpModedata.AddressCount != 0 && IpModedata.AddressList != NULL) {
+    CopyMem (
+      (VOID *)Instance->SubnetAddrInfoIPv6,
+      (VOID *)&IpModedata.AddressList,
+      IpModedata.AddressCount * sizeof (EFI_IP6_ADDRESS_INFO)
+      );
+    FreePool(IpModedata.AddressList);
+  }
+
   return EFI_SUCCESS;
 }

--
2.37.1.windows.1







Re: [edk2-platforms][PATCH V4 05/14] Platform/Loongson: Add MmuLib.

maobibo
 

在 2022/10/21 15:11, xianglai li 写道:
Read the memory map information through the QemuFwCfg interface,
then build the page table through the memory map information,
and finally enable Mmu.

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

Signed-off-by: xianglai li <lixianglai@...>
---
.../LoongArchQemuPkg/Include/Library/MmuLib.h | 85 ++
.../LoongArchQemuPkg/Library/MmuLib/Mmu.S | 35 +
.../Library/MmuLib/MmuBaseLib.inf | 35 +
.../Library/MmuLib/MmuBaseLibPei.inf | 42 +
.../Library/MmuLib/MmuLibCore.c | 908 ++++++++++++++++++
.../Library/MmuLib/MmuLibCore.h | 39 +
.../Library/MmuLib/MmuLibCorePei.c | 236 +++++
.../LoongArchQemuPkg/Library/MmuLib/mmu.h | 104 ++
.../LoongArchQemuPkg/Library/MmuLib/page.h | 267 +++++
.../LoongArchQemuPkg/Library/MmuLib/pte.h | 57 ++
10 files changed, 1808 insertions(+)
create mode 100644 Platform/Loongson/LoongArchQemuPkg/Include/Library/MmuLib.h
create mode 100644 Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/Mmu.S
create mode 100644 Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuBaseLib.inf
create mode 100644 Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuBaseLibPei.inf
create mode 100644 Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuLibCore.c
create mode 100644 Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuLibCore.h
create mode 100644 Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuLibCorePei.c
create mode 100644 Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/mmu.h
create mode 100644 Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/page.h
create mode 100644 Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/pte.h

diff --git a/Platform/Loongson/LoongArchQemuPkg/Include/Library/MmuLib.h b/Platform/Loongson/LoongArchQemuPkg/Include/Library/MmuLib.h
new file mode 100644
index 0000000000..6c501eca07
--- /dev/null
+++ b/Platform/Loongson/LoongArchQemuPkg/Include/Library/MmuLib.h
@@ -0,0 +1,85 @@
+/** @file
+
+ Copyright (c) 2021 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+ @par Glossary:
+ - EXC - execute
+**/
+#ifndef MMU_LIB_H_
+#define MMU_LIB_H_
+/**
+ write operation is performed Count times from the first element of Buffer.
+Convert EFI Attributes to Loongarch Attributes.
+ @param[in] EfiAttributes Efi Attributes.
+
+ @retval LoongArch Attributes.
+**/
+UINTN
+EfiAttributeToLoongArchAttribute (
+ IN UINTN EfiAttributes
+ );
+
+/**
+ Finds the length and memory properties of the memory region corresponding to the specified base address.
+
+ @param[in] BaseAddress To find the base address of the memory region.
+ @param[in] EndAddress To find the end address of the memory region.
+ @param[out] RegionLength The length of the memory region found.
+ @param[out] RegionAttributes Properties of the memory region found.
+
+ @retval EFI_SUCCESS The corresponding memory area was successfully found
+ EFI_NOT_FOUND No memory area found
+**/
+EFI_STATUS
+GetLoongArchMemoryRegion (
+ IN UINTN BaseAddress,
+ IN UINTN EndAddress,
+ OUT UINTN *RegionLength,
+ OUT UINTN *RegionAttributes
+ );
+
+/**
+ Sets the Attributes of the specified memory region
+
+ @param[in] BaseAddress The base address of the memory region to set the Attributes.
+ @param[in] Length The length of the memory region to set the Attributes.
+ @param[in] Attributes The Attributes to be set.
+
+ @retval EFI_SUCCESS The Attributes was set successfully
+
+**/
+EFI_STATUS
+LoongArchSetMemoryAttributes (
+ IN EFI_PHYSICAL_ADDRESS BaseAddress,
+ IN UINTN Length,
+ IN UINTN Attributes
+ );
+
+/**
+ Sets the non-executable Attributes for the specified memory region
+
+ @param[in] BaseAddress The base address of the memory region to set the Attributes.
+ @param[in] Length The length of the memory region to set the Attributes.
+
+ @retval EFI_SUCCESS The Attributes was set successfully
+**/
+EFI_STATUS
+LoongArchSetMemoryRegionNoExec (
+ IN EFI_PHYSICAL_ADDRESS BaseAddress,
+ IN UINTN Length
+ );
+/**
+ Create a page table and initialize the MMU.
+
+ @param[] VOID
+
+ @retval VOID
+**/
+VOID
+EFIAPI
+ConfigureMmu (
+ VOID
+ );
+#endif
diff --git a/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/Mmu.S b/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/Mmu.S
new file mode 100644
index 0000000000..a697b54e65
--- /dev/null
+++ b/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/Mmu.S
@@ -0,0 +1,35 @@
+#------------------------------------------------------------------------------
+#
+# LoongArch for LoongArch
+#
+# Copyright (c) 2021 Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#-----------------------------------------------------------------------------
+
+#ifndef _KERNEL
+#define _KERNEL
+#endif
+
+#include "Library/Cpu.h"
+#include "LoongArchAsmMacro.h"
+
+# Query the page table.
+#
+# @param VOID
+#
+# @retval VOID
+ASM_FUNC(HandleTlbRefill)
+ csrwr T0, LOONGARCH_CSR_TLBRSAVE
+ csrrd T0, LOONGARCH_CSR_PGD
+ lddir T0, T0, 3 #Put pud BaseAddress into T0
+ lddir T0, T0, 2 #Put pmd BaseAddress into T0
+ lddir T0, T0, 1 #Put pte BaseAddress into T0
+ ldpte T0, 0
+ ldpte T0, 1
+ tlbfill
+ csrrd T0, LOONGARCH_CSR_TLBRSAVE
+ ertn
+.globl HandleTlbRefillEnd
+HandleTlbRefillEnd:
diff --git a/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuBaseLib.inf b/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuBaseLib.inf
new file mode 100644
index 0000000000..d8cfe6776e
--- /dev/null
+++ b/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuBaseLib.inf
@@ -0,0 +1,35 @@
+## @file
+#
+# Copyright (c) 2021 Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = MmuBaseLib
+ FILE_GUID = da8f0232-fb14-42f0-922c-63104d2c70be
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = MmuLib
+
+ CONSTRUCTOR = MmuInitialize
+[Sources.common]
+ MmuLibCore.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ Platform/Loongson/LoongArchQemuPkg/Loongson.dec
+
+[PCD]
+ gLoongArchQemuPkgTokenSpaceGuid.PcdSwapPageDir
+ gLoongArchQemuPkgTokenSpaceGuid.PcdInvalidPgd
+ gLoongArchQemuPkgTokenSpaceGuid.PcdInvalidPud
+ gLoongArchQemuPkgTokenSpaceGuid.PcdInvalidPmd
+ gLoongArchQemuPkgTokenSpaceGuid.PcdInvalidPte
+
+[LibraryClasses]
+ MemoryAllocationLib
+ PcdLib
+ DebugLib
diff --git a/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuBaseLibPei.inf b/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuBaseLibPei.inf
new file mode 100644
index 0000000000..f6a3cab45f
--- /dev/null
+++ b/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuBaseLibPei.inf
@@ -0,0 +1,42 @@
+## @file
+#
+# Copyright (c) 2021 Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = MmuPeiLib
+ FILE_GUID = da8f0232-fb14-42f0-922c-63104d2c70bd
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = MmuLib | SEC PEIM
+
+[Sources.common]
+ MmuLibCorePei.c
+ Mmu.S
+ MmuLibCore.h
+ MmuLibCore.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ Platform/Loongson/LoongArchQemuPkg/Loongson.dec
+ OvmfPkg/OvmfPkg.dec
+
+[PCD]
+ gLoongArchQemuPkgTokenSpaceGuid.PcdSwapPageDir
+ gLoongArchQemuPkgTokenSpaceGuid.PcdInvalidPgd
+ gLoongArchQemuPkgTokenSpaceGuid.PcdInvalidPud
+ gLoongArchQemuPkgTokenSpaceGuid.PcdInvalidPmd
+ gLoongArchQemuPkgTokenSpaceGuid.PcdInvalidPte
+ gLoongArchQemuPkgTokenSpaceGuid.PcdFlashSecFvSize
+ gLoongArchQemuPkgTokenSpaceGuid.PcdFlashSecFvBase
+ gLoongArchQemuPkgTokenSpaceGuid.PcdRamSize
+
+[LibraryClasses]
+ MemoryAllocationLib
+ PcdLib
+ DebugLib
+ QemuFwCfgLib
diff --git a/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuLibCore.c b/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuLibCore.c
new file mode 100644
index 0000000000..d737759ad2
--- /dev/null
+++ b/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuLibCore.c
@@ -0,0 +1,908 @@
+/** @file
+
+ Copyright (c) 2021 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+ @par Glossary:
+ - Pgd or Pgd or PGD - Page Global Directory
+ - Pud or Pud or PUD - Page Upper Directory
+ - Pmd or Pmd or PMD - Page Middle Directory
+ - Pte or pte or PTE - Page Table Entry
+ - Val or VAL or val - Value
+ - Dir - Directory
+**/
+#include <Uefi.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include "Library/Cpu.h"
+#include "pte.h"
+#include "page.h"
+#include "mmu.h"
+
+BOOLEAN mMmuInited = FALSE;
+/**
+ Check to see if mmu successfully initializes.
+
+ @param VOID.
+
+ @retval TRUE Initialization has been completed.
+ FALSE Initialization did not complete.
+**/
+BOOLEAN
+MmuIsInit (VOID) {
+ if ((mMmuInited == TRUE) ||
+ (PcdGet64 (PcdSwapPageDir) != 0)) {
+ return TRUE;
+ }
+ return FALSE;
+}
+
+/**
+ Iterates through the page directory to initialize it.
+
+ @param Dst A pointer to the directory of the page to initialize.
+ @param Num The number of page directories to initialize.
+ @param Src A pointer to the data used to initialize the page directory.
+
+ @retval VOID.
+**/
+VOID
+PageDirInit (
+ IN VOID *Dst,
+ IN UINTN Num,
+ IN VOID *Src
+ )
+{
+ UINTN *Ptr;
+ UINTN *End;
+ UINTN Entry;
+
+ Entry = (UINTN)Src;
+ Ptr = (UINTN *)Dst;
+ End = Ptr + Num;
+
+ for ( ;Ptr < End; Ptr++) {
+ *Ptr = Entry;
+ }
+
+ return ;
+}
+/**
+ Gets the virtual address corresponding to the page global directory table entry.
+
+ @param Address the virtual address for the table entry.
+
+ @retval PGD A pointer to get the table item.
+**/
+PGD *
+PgdOffset (
+ IN UINTN Address
+ )
+{
+ return ((PGD *)PcdGet64 (PcdSwapPageDir)) + PGD_INDEX (Address);
+}
+/**
+ Gets the virtual address corresponding to the page upper directory table entry.
+
+ @param Pgd A pointer to a page global directory table entry.
+ @param Address the virtual address for the table entry.
+
+ @retval PUD A pointer to get the table item.
+**/
+PUD *
+PudOffset (
+ IN PGD *Pgd,
+ IN UINTN Address
+ )
+{
+ UINTN PgdVal = (UINTN)PGD_VAL (*Pgd);
+ return (PUD *)PgdVal + PUD_INDEX (Address);
+}
+/**
+ Gets the virtual address corresponding to the page middle directory table entry.
+
+ @param Pud A pointer to a page upper directory table entry.
+ @param Address the virtual address for the table entry.
+
+ @retval PMD A pointer to get the table item.
+**/
+PMD *
+PmdOffset (
+ IN PUD *Pud,
+ IN UINTN Address
+ )
+{
+ UINTN PudVal = PUD_VAL (*Pud);
+ return (PMD *)PudVal + PMD_INDEX (Address);
+}
+/**
+ Gets the virtual address corresponding to the page table entry.
+
+ @param Pmd A pointer to a page middle directory table entry.
+ @param Address the virtual address for the table entry.
+
+ @retval PTE A pointer to get the table item.
+**/
+PTE *
+PteOffset (
+ IN PMD *Pmd,
+ IN UINTN Address
+ )
+{
+ UINTN PmdVal = (UINTN)PMD_VAL (*Pmd);
+ return (PTE *)PmdVal + PTE_INDEX (Address);
+}
+
+/**
+ Sets the value of the page table entry.
+
+ @param Pte A pointer to a page table entry.
+ @param PteVal The value of the page table entry to set.
+
+ @retval VOID
+**/
+VOID
+SetPte (
+ IN PTE *Pte,
+ IN PTE PteVal
+ )
+{
+ *Pte = PteVal;
+}
+/**
+ Sets the value of the page global directory.
+
+ @param Pgd A pointer to a page global directory.
+ @param Pud The value of the page global directory to set.
+
+ @retval VOID
+**/
+VOID
+SetPgd (
+ IN PGD *Pgd,
+ IN PUD *Pud
+ )
+{
+ *Pgd = (PGD) {((UINTN)Pud)};
+}
+
+/**
+ Sets the value of the page upper directory.
+
+ @param Pud A pointer to a page upper directory.
+ @param Pmd The value of the page upper directory to set.
+
+ @retval VOID
+**/
+VOID
+SetPud (
+ IN PUD *Pud,
+ IN PMD *Pmd
+ )
+{
+ *Pud = (PUD) {((UINTN)Pmd)};
+}
+
+/**
+ Sets the value of the page middle directory.
+
+ @param Pmd A pointer to a page middle directory.
+ @param Pte The value of the page middle directory to set.
+
+ @retval VOID
+**/
+VOID
+SetPmd (
+ IN PMD *Pmd,
+ IN PTE *Pte
+ )
+{
+ *Pmd = (PMD) {((UINTN)Pte)};
+}
+/**
+ Free up memory space occupied by page tables.
+
+ @param Pte A pointer to the page table.
+
+ @retval VOID
+**/
+VOID
+PteFree (
+ IN PTE *Pte
+ )
+{
+ FreePages ((VOID *)Pte, 1);
+}
+/**
+ Free up memory space occupied by page middle directory.
+
+ @param Pmd A pointer to the page middle directory.
+
+ @retval VOID
+**/
+VOID
+PmdFree (
+ IN PMD *Pmd
+ )
+{
+ FreePages ((VOID *)Pmd, 1);
+}
+/**
+ Free up memory space occupied by page upper directory.
+
+ @param Pud A pointer to the page upper directory.
+
+ @retval VOID
+**/
+VOID
+PudFree (
+ IN PUD *Pud
+ )
+{
+ FreePages ((VOID *)Pud, 1);
+}
+/**
+ Requests the memory space required for the page upper directory,
+ initializes it, and places it in the specified page global directory
+
+ @param Pgd A pointer to the page global directory.
+
+ @retval EFI_SUCCESS Memory request successful.
+ @retval EFI_OUT_OF_RESOURCES Resource exhaustion cannot be requested to memory.
+**/
+INTN
+PudAlloc (
+ IN PGD *Pgd
+ )
+{
+ PUD *Pud = (PUD *) AllocatePages (1);
+ if (!Pud) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ PageDirInit ((VOID *)Pud, ENTRYS_PER_PUD, (VOID *)PcdGet64 (PcdInvalidPmd));
+
+ if (pgd_none (*Pgd)) {
+ SetPgd (Pgd, Pud);
+ } else { /* Another has populated it */
+ PudFree (Pud);
+ }
+
+ return EFI_SUCCESS;
+}
+/**
+ Requests the memory space required for the page middle directory,
+ initializes it, and places it in the specified page upper directory
+
+ @param Pud A pointer to the page upper directory.
+
+ @retval EFI_SUCCESS Memory request successful.
+ @retval EFI_OUT_OF_RESOURCES Resource exhaustion cannot be requested to memory.
+**/
+EFI_STATUS
+PmdAlloc (
+ IN PUD *Pud
+ )
+{
+ PMD *Pmd;
+
+ Pmd = (PMD *) AllocatePages (1);
+ if (!Pmd) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ PageDirInit ((VOID *)Pmd, ENTRYS_PER_PMD, (VOID *)PcdGet64 (PcdInvalidPte));
+
+ if (pud_none (*Pud)) {
+ SetPud (Pud, Pmd);
+ } else {/* Another has populated it */
+ PmdFree (Pmd);
+ }
+
+ return EFI_SUCCESS;
+}
+/**
+ Requests the memory space required for the page table,
+ initializes it, and places it in the specified page middle directory
+
+ @param Pmd A pointer to the page middle directory.
+
+ @retval EFI_SUCCESS Memory request successful.
+ @retval EFI_OUT_OF_RESOURCES Resource exhaustion cannot be requested to memory.
+**/
+INTN
+PteAlloc (
+ IN PMD *Pmd
+ )
+{
+ PTE *Pte;
+
+ Pte = (PTE *) AllocatePages (1);
+ if (!Pte) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ Pte = ZeroMem (Pte, EFI_PAGE_SIZE);
+
+ if (pmd_none (*Pmd)) {
+ SetPmd (Pmd, Pte);
+ } else { /* Another has populated it */
+ PteFree (Pte);
+ }
+
+ return EFI_SUCCESS;
+}
+/**
+ Requests the memory space required for the page upper directory,
+ initializes it, and places it in the specified page global directory,
+ and get the page upper directory entry corresponding to the virtual address
+
+ @param Pgd A pointer to the page global directory.
+
+ @retval Gets the page upper directory entry
+**/
+PUD *
+PudAllocGet (
+ IN PGD *Pgd,
+ IN UINTN Address
+ )
+{
+ return ((pgd_none (*(Pgd)) && PudAlloc (Pgd)) ?
+ NULL : PudOffset (Pgd, Address));
+}
+/**
+ Requests the memory space required for the page middle directory,
+ initializes it, and places it in the specified page upper directory,
+ and get the page middle directory entry corresponding to the virtual address
+
+ @param Pud A pointer to the page upper directory.
+
+ @retval Gets the page middle directory entry
+**/
+PMD *
+PmdAllocGet (
+ IN PUD *Pud,
+ IN UINTN Address
+ )
+{
+ PMD * ret = (pud_none (*Pud) && PmdAlloc (Pud))?
+ NULL: PmdOffset (Pud, Address);
+ DEBUG ((DEBUG_VERBOSE, "%a %d PudVal %p PmdOffset %p PMD_INDEX %p .\n", __func__, __LINE__,
+ Pud->PudVal, PmdOffset (Pud, Address), PMD_INDEX (Address) ));
+
+ return ret;
+}
+/**
+ Requests the memory space required for the page table,
+ initializes it, and places it in the specified page middle directory,
+ and get the page table entry corresponding to the virtual address
+
+ @param Pmd A pointer to the page upper directory.
+
+ @retval Gets the page table entry
+**/
+PTE *
+PteAllocGet (
+ IN PMD *Pmd,
+ IN UINTN Address
+ )
+{
+ return (pmd_none (*Pmd) && PteAlloc (Pmd))?
+ NULL: PteOffset (Pmd, Address);
+}
+ /**
+ Convert page middle directory table entry to tlb entry.
+
+ @param PmdVal page middle directory table entry value.
+
+ @retval tlb entry value.
+ **/
+UINTN
+PmdToTlbEntry (
+ UINTN PmdVal
+ )
+{
+ UINTN Value;
+
+ Value = PmdVal ^ PAGE_HUGE;
+ Value |= ((Value & PAGE_HGLOBAL) >>
+ (PAGE_HGLOBAL_SHIFT - PAGE_GLOBAL_SHIFT));
+
+ return Value;
+}
+
+ /**
+ Update huge tlb.
+
+ @param address The address corresponding to tlb.
+ @param Pte A pointer to the page table entry.
+
+ @retval VOID.
+ **/
+VOID
+UpdateHugeTlb (
+ IN UINTN address,
+ PTE *Pte)
+{
+ INTN Idx;
+ UINTN TlbEntry;
+ address &= (PAGE_MASK << 1);
+ LOONGARCH_CSR_WRITEQ (address, LOONGARCH_CSR_TLBEHI);
+ LOONGARCH_TLB_SRCH();
+ LOONGARCH_CSR_READQ (Idx, LOONGARCH_CSR_TLBIDX);
+
+ if (Idx < 0) {
+ return ;
+ }
+ WRITE_CSR_PAGE_SIZE (HUGE_PAGE_SIZE);
+ TlbEntry = PmdToTlbEntry(PTE_VAL (*Pte));
+ LOONGARCH_CSR_WRITEQ(TlbEntry, LOONGARCH_CSR_TLBELO0);
+ LOONGARCH_CSR_WRITEQ(TlbEntry + (HUGE_PAGE_SIZE >> 1), LOONGARCH_CSR_TLBELO1);
+ LOONGARCH_TLB_WR ();
+
+ WRITE_CSR_PAGE_SIZE (DEFAULT_PAGE_SIZE);
+
+ return ;
+}
+ /**
+ Update tlb.
+
+ @param address The address corresponding to tlb.
+ @param Pte A pointer to the page table entry.
+
+ @retval VOID.
+ **/
+VOID
+UpdateTlb (
+ IN UINTN address,
+ PTE *Pte)
+{
+ INTN Idx;
+ if (IS_HUGE_PAGE (Pte->PteVal)) {
+ return UpdateHugeTlb(address, Pte);
+ }
+
+ address &= (PAGE_MASK << 1);
+ LOONGARCH_CSR_WRITEQ (address, LOONGARCH_CSR_TLBEHI);
+ LOONGARCH_TLB_SRCH();
+ LOONGARCH_CSR_READQ (Idx, LOONGARCH_CSR_TLBIDX);
+
+ if (Idx < 0) {
+ return ;
+ }
+
+ if ((UINTN)Pte & sizeof(PTE)) {
+ Pte--;
+ }
+
+ WRITE_CSR_PAGE_SIZE (DEFAULT_PAGE_SIZE);
+ LOONGARCH_CSR_WRITEQ(PTE_VAL (*Pte), LOONGARCH_CSR_TLBELO0);
+ Pte++;
+ LOONGARCH_CSR_WRITEQ(PTE_VAL (*Pte), LOONGARCH_CSR_TLBELO1);
+ LOONGARCH_TLB_WR ();
+
+ return ;
+}
+
+/**
+ Gets the physical address of the page table entry corresponding to the specified virtual address.
+
+ @param Address the corresponding virtual address of the page table entry.
+
+ @retval A pointer to the page table entry.
+ @retval NULL
+**/
+PTE *
+GetPteAddress (
+ IN UINTN Address
+ )
+{
+ PGD *Pgd;
+ PUD *Pud;
+ PMD *Pmd;
+
+ Pgd = PgdOffset (Address);
+
+ if (pgd_none (*Pgd)) {
+ return NULL;
+ }
+
+ Pud = PudOffset (Pgd, Address);
+
+ if (pud_none (*Pud)) {
+ return NULL;
+ }
+
+ Pmd = PmdOffset (Pud, Address);
+ if (pmd_none (*Pmd)) {
+ return NULL;
+ }
+
+ if (IS_HUGE_PAGE (Pmd->PmdVal)) {
+ return ((PTE *)Pmd);
+ }
+
+ return PteOffset (Pmd, Address);
+}
+/**
+ Establishes a page table entry based on the specified memory region.
+
+ @param Pmd A pointer to the page middle directory.
+ @param Address The memory space start address.
+ @param End The end address of the memory space.
+ @param Attributes Memory space Attributes.
+
+ @retval EFI_SUCCESS The page table entry was created successfully.
+ @retval EFI_OUT_OF_RESOURCES Page table entry establishment failed due to resource exhaustion.
+**/
+EFI_STATUS
+MemoryMapPteRange (
+ IN PMD *Pmd,
+ IN UINTN Address,
+ IN UINTN End,
+ IN UINTN Attributes
+ )
+{
+ PTE *Pte;
+ PTE PteVal;
+ BOOLEAN UpDate;
+
+ Pte = PteAllocGet (Pmd, Address);
+ if (!Pte) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ do {
+ UpDate = FALSE;
+ PteVal = MAKE_PTE (Address, Attributes);
+ DEBUG ((DEBUG_VERBOSE,
+ "%a %d Address %p PGD_INDEX %p PUD_INDEX %p PMD_INDEX %p PTE_INDEX %p MAKE_PTE %p\n",
+ __func__, __LINE__, Address, PGD_INDEX (Address), PUD_INDEX (Address), PMD_INDEX (Address),
+ PTE_INDEX (Address), PteVal));
+
+ if ((!pte_none (*Pte)) &&
+ (PTE_VAL(*Pte) != PTE_VAL(PteVal)))
+ {
+ UpDate = TRUE;
+ }
+
+ SetPte (Pte, PteVal);
+ if (UpDate) {
+ UpdateTlb (Address, Pte);
+ }
+ } while (Pte++, Address += EFI_PAGE_SIZE, Address != End);
+
+ return EFI_SUCCESS;
+}
+/**
+ Establishes a page middle directory based on the specified memory region.
+
+ @param Pud A pointer to the page upper directory.
+ @param Address The memory space start address.
+ @param End The end address of the memory space.
+ @param Attributes Memory space Attributes.
+
+ @retval EFI_SUCCESS The page middle directory was created successfully.
+ @retval EFI_OUT_OF_RESOURCES Page middle directory establishment failed due to resource exhaustion.
+**/
+EFI_STATUS
+MemoryMapPmdRange (
+ IN PUD *Pud,
+ IN UINTN Address,
+ IN UINTN End,
+ IN UINTN Attributes
+ )
+{
+ PMD *Pmd;
+ PTE *Pte;
+ UINTN Next;
+ UINTN AddressStart_HugePage;
+ UINTN AddressEnd_HugePage;
+
+ Pmd = PmdAllocGet (Pud, Address);
+ if (!Pmd) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ do {
+ Next = PMD_ADDRESS_END (Address, End);
+ if (((Address & (~PMD_MASK)) == 0) &&
+ ((Next & (~PMD_MASK)) == 0) &&
+ (pmd_none (*Pmd)))
+ {
+ DEBUG ((DEBUG_VERBOSE,
+ "%a %d Address %p PGD_INDEX %p PUD_INDEX %p PMD_INDEX %p MAKE_HUGE_PTE %p\n",
+ __func__, __LINE__, Address, PGD_INDEX (Address), PUD_INDEX (Address), PMD_INDEX (Address),
+ MAKE_HUGE_PTE (Address, Attributes)));
+
+ SetPmd (Pmd, (PTE *)MAKE_HUGE_PTE (Address, Attributes));
+ } else {
+ if ((pmd_none (*Pmd)) ||
+ ((!pmd_none (*Pmd)) &&
+ (!IS_HUGE_PAGE (Pmd->PmdVal))))
+ {
+ if (MemoryMapPteRange (Pmd, Address, Next, Attributes)) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ } else {
+ SetPmd (Pmd, (PTE *)PcdGet64 (PcdInvalidPte));
+ AddressStart_HugePage = Address & PMD_MASK;
+ AddressEnd_HugePage = AddressStart_HugePage + HUGE_PAGE_SIZE;
+ if (MemoryMapPteRange (Pmd, AddressStart_HugePage, AddressEnd_HugePage, Attributes)) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ Pte = GetPteAddress (AddressStart_HugePage);
+ if (Pte == NULL) {
+ continue ;
+ }
+ UpdateTlb (AddressStart_HugePage, Pte);
+ if (AddressEnd_HugePage > End) {
+ Next = End;
+ }
+ }
+ }
+ } while (Pmd++, Address = Next, Address != End);
+
+ return 0;
+}
+/**
+ Establishes a page upper directory based on the specified memory region.
+
+ @param Pgd A pointer to the page global directory.
+ @param Address The memory space start address.
+ @param End The end address of the memory space.
+ @param Attributes Memory space Attributes.
+
+ @retval EFI_SUCCESS The page upper directory was created successfully.
+ @retval EFI_OUT_OF_RESOURCES Page upper directory establishment failed due to resource exhaustion.
+**/
+EFI_STATUS
+MemoryMapPudRange (
+ IN PGD *Pgd,
+ IN UINTN Address,
+ IN UINTN End,
+ IN UINTN Attributes
+ )
+{
+ PUD *Pud;
+ UINTN Next;
+
+ Pud = PudAllocGet (Pgd, Address);
+ if (!Pud) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ do {
+ Next = PUD_ADDRESS_END (Address, End);
+ if (MemoryMapPmdRange (Pud, Address, Next, Attributes)) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ } while (Pud++, Address = Next, Address != End);
+ return EFI_SUCCESS;
+}
+/**
+ Establishes a page global directory based on the specified memory region.
+
+ @param Start The memory space start address.
+ @param End The end address of the memory space.
+ @param Attributes Memory space Attributes.
+
+ @retval EFI_SUCCESS The page global directory was created successfully.
+ @retval EFI_OUT_OF_RESOURCES Page global directory establishment failed due to resource exhaustion.
+**/
+EFI_STATUS
+MemoryMapPageRange (
+ IN UINTN Start,
+ IN UINTN End,
+ IN UINTN Attributes
+ )
+{
+ PGD *Pgd;
+ UINTN Next;
+ UINTN Address = Start;
+ EFI_STATUS Err;
+
+ Pgd = PgdOffset (Address);
+ do {
+ Next = PGD_ADDRESS_END (Address, End);
+ Err = MemoryMapPudRange (Pgd, Address, Next, Attributes);
+ if (Err) {
+ return Err;
+ }
+ } while (Pgd++, Address = Next, Address != End);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Page tables are established from memory-mapped tables.
+
+ @param MemoryRegion A pointer to a memory-mapped table entry.
+
+ @retval EFI_SUCCESS The page table was created successfully.
+ @retval EFI_OUT_OF_RESOURCES Page table establishment failed due to resource exhaustion.
+**/
+EFI_STATUS
+FillTranslationTable (
+ IN MEMORY_REGION_DESCRIPTOR *MemoryRegion
+ )
+{
+ return MemoryMapPageRange (MemoryRegion->VirtualBase,
+ (MemoryRegion->Length + MemoryRegion->VirtualBase),
+ MemoryRegion->Attributes);
+}
+
+/**
+ write operation is performed Count times from the first element of Buffer.
+Convert EFI Attributes to Loongarch Attributes.
+ @param[in] EfiAttributes Efi Attributes.
+
+ @retval LoongArch Attributes.
+**/
+UINTN
+EfiAttributeToLoongArchAttribute (
+ IN UINTN EfiAttributes
+ )
+{
+ UINTN LoongArchAttributes = PAGE_VALID | PAGE_DIRTY | CACHE_CC | PAGE_USER;
I just think that PAGE_KERNEL need be used here rather than PAGE_USER,
it can only be accessed with kernel priviledge.


+ switch (EfiAttributes & EFI_MEMORY_CACHETYPE_MASK) {
+ case EFI_MEMORY_UC:
+ LoongArchAttributes |= CACHE_SUC;
+ break;
+ case EFI_MEMORY_WC:
+ case EFI_MEMORY_WT:
+ case EFI_MEMORY_WB:
+ LoongArchAttributes |= CACHE_CC;
+ break;
+ default :
+ LoongArchAttributes |= CACHE_CC;
+ break;
+ }
+
+ // Write protection attributes
+ if ((EfiAttributes & EFI_MEMORY_RO) != 0) {
+ LoongArchAttributes &= ~PAGE_DIRTY;
+ }
+
+ //eXecute protection attribute
+ if ((EfiAttributes & EFI_MEMORY_XP) != 0) {
+ LoongArchAttributes |= PAGE_NO_EXEC;
+ }
+
+ return LoongArchAttributes;
+}
+
+/**
+ Finds the length and memory properties of the memory region corresponding to the specified base address.
+
+ @param[in] BaseAddress To find the base address of the memory region.
+ @param[in] EndAddress To find the end address of the memory region.
+ @param[out] RegionLength The length of the memory region found.
+ @param[out] RegionAttributes Properties of the memory region found.
+
+ @retval EFI_SUCCESS The corresponding memory area was successfully found
+ EFI_NOT_FOUND No memory area found
+**/
+EFI_STATUS
+GetLoongArchMemoryRegion (
+ IN UINTN BaseAddress,
+ IN UINTN EndAddress,
+ OUT UINTN *RegionLength,
+ OUT UINTN *RegionAttributes
+ )
+{
+ PTE *Pte;
+ UINTN Attributes;
+ UINTN AttributesTmp;
+ UINTN MaxAddress;
+ MaxAddress = LShiftU64 (1ULL, MAX_VA_BITS) - 1;
+ Pte = GetPteAddress (BaseAddress);
+
+ if (!MmuIsInit ()) {
+ return EFI_SUCCESS;
+ }
+ if (Pte == NULL) {
+ return EFI_NOT_FOUND;
+ }
+ Attributes = GET_PAGE_ATTRIBUTES (*Pte);
+ if (IS_HUGE_PAGE (Pte->PteVal)) {
+ *RegionAttributes = Attributes & (~(PAGE_HUGE));
+ *RegionLength += HUGE_PAGE_SIZE;
+ } else {
+ *RegionLength += EFI_PAGE_SIZE;
+ *RegionAttributes = Attributes;
+ }
+
+ while (BaseAddress <= MaxAddress) {
+ Pte = GetPteAddress (BaseAddress);
+ if (Pte == NULL) {
+ return EFI_SUCCESS;
+ }
+ AttributesTmp = GET_PAGE_ATTRIBUTES (*Pte);
+ if (IS_HUGE_PAGE (Pte->PteVal)) {
+ if (AttributesTmp == Attributes) {
+ *RegionLength += HUGE_PAGE_SIZE;
+ }
+ BaseAddress += HUGE_PAGE_SIZE;
+ } else {
+ if (AttributesTmp == Attributes) {
+ *RegionLength += EFI_PAGE_SIZE;
+ }
+ BaseAddress += EFI_PAGE_SIZE;
+ }
+
+ if (BaseAddress > EndAddress) {
+ break;
+ }
+ }
+ return EFI_SUCCESS;
+}
+
+/**
+ Sets the Attributes of the specified memory region
+
+ @param[in] BaseAddress The base address of the memory region to set the Attributes.
+ @param[in] Length The length of the memory region to set the Attributes.
+ @param[in] Attributes The Attributes to be set.
+
+ @retval EFI_SUCCESS The Attributes was set successfully
+
+**/
+EFI_STATUS
+LoongArchSetMemoryAttributes (
+ IN EFI_PHYSICAL_ADDRESS BaseAddress,
+ IN UINTN Length,
+ IN UINTN Attributes
+ )
+{
+
+ if (!MmuIsInit ()) {
+ return EFI_SUCCESS;
+ }
+ Attributes = EfiAttributeToLoongArchAttribute (Attributes);
+ DEBUG ((DEBUG_VERBOSE, "%a %d %p %p %p.\n", __func__, __LINE__, BaseAddress , Length, Attributes));
+ MemoryMapPageRange (BaseAddress, BaseAddress + Length, Attributes);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Sets the non-executable Attributes for the specified memory region
+
+ @param[in] BaseAddress The base address of the memory region to set the Attributes.
+ @param[in] Length The length of the memory region to set the Attributes.
+
+ @retval EFI_SUCCESS The Attributes was set successfully
+**/
+EFI_STATUS
+LoongArchSetMemoryRegionNoExec (
+ IN EFI_PHYSICAL_ADDRESS BaseAddress,
+ IN UINTN Length
+ )
+{
+ if (MmuIsInit ()) {
+ Length = EFI_PAGES_TO_SIZE (EFI_SIZE_TO_PAGES (Length));
+ LoongArchSetMemoryAttributes (BaseAddress, Length, EFI_MEMORY_XP);
+ }
+ return EFI_SUCCESS;
+}
+
+/**
+ Check to see if mmu successfully initializes and saves the result.
+
+ @param VOID.
+
+ @retval EFI_SUCCESS Initialization succeeded.
+**/
+EFI_STATUS
+MmuInitialize (VOID)
+{
+ if (PcdGet64 (PcdSwapPageDir) != 0) {
+ mMmuInited = TRUE;
+ }
+
+ return EFI_SUCCESS;
+}
diff --git a/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuLibCore.h b/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuLibCore.h
new file mode 100644
index 0000000000..e9f294b356
--- /dev/null
+++ b/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuLibCore.h
@@ -0,0 +1,39 @@
+/** @file
+
+ Copyright (c) 2021 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+ @par Glossary:
+ - Dir - Directory
+**/
+#ifndef MMU_LIB_CORE_H_
+#define MMU_LIB_CORE_H_
+/**
+ Iterates through the page directory to initialize it.
+
+ @param Dst A pointer to the directory of the page to initialize.
+ @param Num The number of page directories to initialize.
+ @param Src A pointer to the data used to initialize the page directory.
+
+ @retval VOID.
+**/
+VOID
+PageDirInit (
+ IN VOID *dest,
+ IN UINTN Count,
+ IN VOID *src
+ );
+/**
+ Page tables are established from memory-mapped tables.
+
+ @param MemoryRegion A pointer to a memory-mapped table entry.
+
+ @retval EFI_SUCCESS The page table was created successfully.
+ @retval EFI_OUT_OF_RESOURCES Page table establishment failed due to resource exhaustion.
+**/
+EFI_STATUS
+FillTranslationTable (
+ IN MEMORY_REGION_DESCRIPTOR *MemoryRegion
+ );
+#endif
diff --git a/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuLibCorePei.c b/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuLibCorePei.c
new file mode 100644
index 0000000000..899f40fd94
--- /dev/null
+++ b/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/MmuLibCorePei.c
@@ -0,0 +1,236 @@
+/** @file
+ Platform PEI driver
+
+ Copyright (c) 2021 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+ @par Glossary:
+ - FwCfg - Firmeware Config
+ - Tlb - Translation Lookaside Buffer
+**/
+#include <Uefi.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include "Library/Cpu.h"
+#include "pte.h"
+#include "page.h"
+#include "mmu.h"
+#include <Library/QemuFwCfgLib.h>
+#include "MmuLibCore.h"
+
+/**
+ Return the Virtual Memory Map of your platform
+
+ This Virtual Memory Map is used by MemoryInitPei Module to initialize the MMU
+ on your platform.
+
+ @param[out] VirtualMemoryMap Array of MEMORY_REGION_DESCRIPTOR
+ describing a Physical-to-Virtual Memory
+ mapping. This array must be ended by a
+ zero-filled entry. The allocated memory
+ will not be freed.
+
+**/
+VOID
+GetMemoryMapFromFwCfg (
+ OUT MEMORY_REGION_DESCRIPTOR **VirtualMemoryMap
+ )
+{
+
+ EFI_STATUS Status;
+ FIRMWARE_CONFIG_ITEM FwCfgItem;
+ UINTN FwCfgSize;
+ LOONGARCH_MEMMAP_ENTRY MemoryMapEntry;
+ LOONGARCH_MEMMAP_ENTRY *StartEntry;
+ LOONGARCH_MEMMAP_ENTRY *pEntry;
+ UINTN Processed;
+ MEMORY_REGION_DESCRIPTOR *VirtualMemoryTable;
+ UINTN Index = 0;
+ ASSERT (VirtualMemoryMap != NULL);
+
+ VirtualMemoryTable = AllocatePool (
+ sizeof (MEMORY_REGION_DESCRIPTOR) *
+ MAX_VIRTUAL_MEMORY_MAP_DESCRIPTORS
+ );
+ VirtualMemoryTable[Index].PhysicalBase = 0x10000000;
+ VirtualMemoryTable[Index].VirtualBase = VirtualMemoryTable[Index].PhysicalBase;
+ VirtualMemoryTable[Index].Length = 0x80000000;
+ VirtualMemoryTable[Index].Attributes = PAGE_VALID | PAGE_USER | CACHE_CC | PAGE_DIRTY;
PAGE_KERNEL need be used here rather than PAGE_USER.
And the memory space from 0x10000000 -- 0x80000000 is mmio space, it should be uncachable. CACHE_SUC should be used here.

+ ++Index;
+
+ Status = QemuFwCfgFindFile ("etc/memmap", &FwCfgItem, &FwCfgSize);
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_ERROR, "%a %d read etc/memmap error Status %d \n", __func__, __LINE__, Status));
+ ZeroMem (&VirtualMemoryTable[Index], sizeof (MEMORY_REGION_DESCRIPTOR));
+ *VirtualMemoryMap = VirtualMemoryTable;
+ return ;
+ }
+ if (FwCfgSize % sizeof MemoryMapEntry != 0) {
+ DEBUG ((DEBUG_ERROR, "no MemoryMapEntry FwCfgSize:%d\n", FwCfgSize));
+ }
+
+ QemuFwCfgSelectItem (FwCfgItem);
+ StartEntry = AllocatePages (EFI_SIZE_TO_PAGES (FwCfgSize));
+ QemuFwCfgReadBytes (FwCfgSize, StartEntry);
+ for (Processed = 0; Processed < (FwCfgSize / sizeof MemoryMapEntry); Processed++) {
+ pEntry = StartEntry + Processed;
+ if (pEntry->Length == 0) {
+ continue;
+ }
+
+ DEBUG ((DEBUG_INFO, "MemmapEntry Base %p length %p type %d\n", pEntry->BaseAddr, pEntry->Length, pEntry->Type));
+ VirtualMemoryTable[Index].PhysicalBase = pEntry->BaseAddr;
+ VirtualMemoryTable[Index].VirtualBase = VirtualMemoryTable[Index].PhysicalBase;
+ VirtualMemoryTable[Index].Length = pEntry->Length;
+ VirtualMemoryTable[Index].Attributes = PAGE_VALID | PAGE_USER | CACHE_CC | PAGE_DIRTY;
+ ++Index;
+ }
+
+ FreePages (StartEntry, EFI_SIZE_TO_PAGES (FwCfgSize));
+ // End of Table
+ ZeroMem (&VirtualMemoryTable[Index], sizeof (MEMORY_REGION_DESCRIPTOR));
+ *VirtualMemoryMap = VirtualMemoryTable;
+ return ;
+}
+
+/**
+ Create a page table and initialize the MMU.
+
+ @param[] VOID
+
+ @retval VOID
+**/
+EFIAPI
+VOID
+ConfigureMmu (VOID)
+{
+ PGD *SwapperPageDir = NULL;
+ PGD *InvalidPgd = NULL;
+ PUD *InvalidPudTable = NULL;
+ PMD *InvalidPmdTable = NULL;
+ PTE *InvalidPteTable = NULL;
+ MEMORY_REGION_DESCRIPTOR *MemoryTable = NULL;
+ RETURN_STATUS PcdStatus;
+ UINTN PgdShift = PGD_SHIFT;
+ UINTN PgdWide = PGD_WIDE;
+ UINTN PudShift = PUD_SHIFT;
+ UINTN PudWide = PUD_WIDE;
+ UINTN PmdShift = PMD_SHIFT;
+ UINTN PmdWide = PMD_WIDE;
+ UINTN PteShift = PTE_SHIFT;
+ UINTN PteWide = PTE_WIDE;
+ UINTN PageEnable = 1 << 4;
+ VOID *TlbReEntry;
+ UINTN PageSize;
+
+ SwapperPageDir = AllocatePages (EFI_SIZE_TO_PAGES (PGD_TABLE_SIZE));
+ InvalidPgd = AllocatePages (EFI_SIZE_TO_PAGES (PGD_TABLE_SIZE));
+ InvalidPudTable = AllocatePages (EFI_SIZE_TO_PAGES (PUD_TABLE_SIZE));
+ InvalidPmdTable = AllocatePages (EFI_SIZE_TO_PAGES (PMD_TABLE_SIZE));
+ InvalidPteTable = AllocatePages (EFI_SIZE_TO_PAGES (PTE_TABLE_SIZE));
+ ZeroMem (InvalidPteTable, PTE_TABLE_SIZE);
+
+ if ((!InvalidPgd) ||
+ (!InvalidPudTable) ||
+ (!InvalidPmdTable) ||
+ (!InvalidPteTable))
+ {
+ goto FreeTranslationTable;
+ }
+
+ /*pgd init*/
+ PageDirInit (SwapperPageDir , ENTRYS_PER_PGD, InvalidPudTable);
+ /*pgd init*/
+ PageDirInit (InvalidPgd, ENTRYS_PER_PGD, InvalidPudTable);
+ /*pud init*/
+ PageDirInit (InvalidPudTable, ENTRYS_PER_PUD, InvalidPmdTable);
+ /*pmd init*/
+ PageDirInit (InvalidPmdTable, ENTRYS_PER_PMD, InvalidPteTable);
+ GetMemoryMapFromFwCfg (&MemoryTable);
+
+ PcdStatus |= PcdSet64S (PcdSwapPageDir, (UINTN)SwapperPageDir);
+ PcdStatus |= PcdSet64S (PcdInvalidPgd, (UINTN)InvalidPgd);
+ PcdStatus |= PcdSet64S (PcdInvalidPud, (UINTN)InvalidPudTable);
+ PcdStatus |= PcdSet64S (PcdInvalidPmd, (UINTN)InvalidPmdTable);
+ PcdStatus |= PcdSet64S (PcdInvalidPte, (UINTN)InvalidPteTable);
+ ASSERT_RETURN_ERROR (PcdStatus);
+
+ while (MemoryTable->Length != 0) {
+ DEBUG ((DEBUG_VERBOSE, "%a %d VirtualBase %p VirtualEnd %p Attributes %p .\n", __func__, __LINE__,
+ MemoryTable->VirtualBase,
+ (MemoryTable->Length + MemoryTable->VirtualBase),
+ MemoryTable->Attributes));
+
+ PcdStatus = FillTranslationTable (MemoryTable);
+ if (EFI_ERROR (PcdStatus)) {
+ goto FreeTranslationTable;
+ }
+ MemoryTable++;
+ }
+
+ /*set page size*/
+ WRITE_CSR_PAGE_SIZE (DEFAULT_PAGE_SIZE);
+ WRITE_CSR_STLB_PAGE_SIZE (DEFAULT_PAGE_SIZE);
+ WRITE_CSR_TLBREFILL_PAGE_SIZE (DEFAULT_PAGE_SIZE);
+ READ_CSR_PAGE_SIZE (PageSize);
+ if (PageSize != DEFAULT_PAGE_SIZE) {
+ goto FreeTranslationTable;
+ }
+
+ TlbReEntry = AllocatePages (1);
+ if (TlbReEntry == NULL) {
+ goto FreeTranslationTable;
+ }
+ CopyMem ((char *)TlbReEntry, HandleTlbRefill, (HandleTlbRefillEnd - HandleTlbRefill));
+ SET_REFILL_TLBBASE ((UINTN)HandleTlbRefill);
+
+ DEBUG ((DEBUG_VERBOSE,
+ "%a %d PteShift %d PteWide %d PmdShift %d PmdWide %d PudShift %d PudWide %d PgdShift %d PgdWide %d.\n",
+ __func__, __LINE__,
+ PteShift, PteWide, PmdShift, PmdWide,PudShift, PudWide, PgdShift, PgdWide));
+
+ LOONGARCH_CSR_WRITEQ (PteShift | PteWide << 5 | PmdShift << 10 | PmdWide << 15 | PudShift << 20 | PudWide << 25,
+ LOONGARCH_CSR_PWCTL0);
+ LOONGARCH_CSR_WRITEQ (PgdShift | PgdWide << 6, LOONGARCH_CSR_PWCTL1);
+ LOONGARCH_CSR_WRITEQ ((UINTN)SwapperPageDir, LOONGARCH_CSR_PGDL);
+ LOONGARCH_CSR_WRITEQ ((UINTN)InvalidPgd, LOONGARCH_CSR_PGDH);
+
+ DEBUG ((DEBUG_INFO, "%a %d Enable Mmu Start PageBassAddress %p.\n", __func__, __LINE__, SwapperPageDir));
+ LOONGARCH_CSR_XCHGQ ( PageEnable, 1 << 4, LOONGARCH_CSR_CRMD);
+ DEBUG ((DEBUG_INFO, "%a %d Enable Mmu End.\n", __func__, __LINE__));
+
+ return ;
+
+FreeTranslationTable:
+ if (SwapperPageDir) {
+ FreePages (SwapperPageDir, EFI_SIZE_TO_PAGES (PGD_TABLE_SIZE));
+ }
+
+ if (InvalidPgd) {
+ FreePages (InvalidPgd, EFI_SIZE_TO_PAGES (PGD_TABLE_SIZE));
+ }
+
+ if (InvalidPudTable) {
+ FreePages (InvalidPudTable, EFI_SIZE_TO_PAGES (PUD_TABLE_SIZE));
+ }
+
+ if (InvalidPmdTable) {
+ FreePages (InvalidPmdTable, EFI_SIZE_TO_PAGES (PMD_TABLE_SIZE));
+ }
+
+ if (InvalidPteTable) {
+ FreePages (InvalidPteTable, EFI_SIZE_TO_PAGES (PTE_TABLE_SIZE));
+ }
+
+ PcdSet64S (PcdSwapPageDir, (UINTN)0);
+ PcdSet64S (PcdInvalidPgd, (UINTN)0);
+ PcdSet64S (PcdInvalidPud, (UINTN)0);
+ PcdSet64S (PcdInvalidPmd, (UINTN)0);
+ PcdSet64S (PcdInvalidPte, (UINTN)0);
+
+ return ;
+}
+
diff --git a/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/mmu.h b/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/mmu.h
new file mode 100644
index 0000000000..50b785bb6e
--- /dev/null
+++ b/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/mmu.h
@@ -0,0 +1,104 @@
+/** @file
+
+ Copyright (c) 2021 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+ @par Glossary:
+ - Tlb or TLB - Translation Lookaside Buffer
+ - CSR - Cpu State Register
+ - PGDL - Page Global Directory Low
+ - PGDH - Page Global Directory High
+ - TLBIDX - TLB Index
+ - TLBREHI - TLB Refill Entry High
+ - PWCTL - Page Walk Control
+ - STLB - Singular Page Size TLB
+ - PS - Page Size
+**/
+#ifndef MMU_H_
+#define MMU_H_
+/*page size 4k*/
+#define DEFAULT_PAGE_SIZE 0x0c
+#define LOONGARCH_CSR_PGDL 0x19 /* Page table base address when VA[47] = 0 */
+#define LOONGARCH_CSR_PGDH 0x1a /* Page table base address when VA[47] = 1 */
+#define LOONGARCH_CSR_TLBIDX 0x10 /* TLB Index, EHINV, PageSize, NP */
+#define LOONGARCH_CSR_TLBEHI 0x11 /* TLB EntryHi */
+#define LOONGARCH_CSR_TLBELO0 0x12 /* TLB EntryLo0 */
+#define LOONGARCH_CSR_TLBELO1 0x13 /* TLB EntryLo1 */
+#define LOONGARCH_CSR_TLBREHI 0x8e /* TLB refill entryhi */
+#define LOONGARCH_CSR_PWCTL0 0x1c /* PWCtl0 */
+#define LOONGARCH_CSR_PWCTL1 0x1d /* PWCtl1 */
+#define LOONGARCH_CSR_STLBPGSIZE 0x1e
+#define CSR_TLBIDX_SIZE_MASK 0x3f000000
+#define CSR_TLBIDX_PS_SHIFT 24
+#define CSR_TLBIDX_SIZE CSR_TLBIDX_PS_SHIFT
+
+/*
+ Set Cpu Status Register STLB Page Size.
+
+ @param val Page Size.
+
+ @retval VOID
+ */
+#define WRITE_CSR_STLB_PAGE_SIZE(val) LOONGARCH_CSR_WRITEQ((val), LOONGARCH_CSR_STLBPGSIZE)
+/*
+ Set Cpu Status Register Page Size.
+
+ @param size Page Size.
+
+ @retval VOID
+ */
+#define WRITE_CSR_PAGE_SIZE(size) LOONGARCH_CSR_XCHGQ((size) << CSR_TLBIDX_SIZE, CSR_TLBIDX_SIZE_MASK, LOONGARCH_CSR_TLBIDX)
+/*
+ Set Cpu Status Register TLBREFILL Page Size.
+
+ @param size Page Size.
+
+ @retval VOID
+ */
+#define WRITE_CSR_TLBREFILL_PAGE_SIZE(size) LOONGARCH_CSR_XCHGQ((size) << CSR_TLBREHI_PS_SHIFT, CSR_TLBREHI_PS, LOONGARCH_CSR_TLBREHI)
+/*
+ Set Cpu Status Register TLBREFILL Base Address.
+
+ @param BaseAddress the code base address of TLB refills .
+
+ @retval VOID
+ */
+#define SET_REFILL_TLBBASE(BaseAddress) LOONGARCH_CSR_WRITEQ((BaseAddress), LOONGARCH_CSR_TLBREBASE);
+/*
+ Get Cpu Status Register Page Size.
+
+ @param val Gets the page size.
+
+ @retval VOID
+ */
+#define READ_CSR_PAGE_SIZE(val) \
+{ \
+ LOONGARCH_CSR_READQ ((val), LOONGARCH_CSR_TLBIDX); \
+ (val) = ((val) & CSR_TLBIDX_SIZE_MASK) >> CSR_TLBIDX_SIZE; \
+}
+
+
+#define CSR_TLBREHI_PS_SHIFT 0
+#define CSR_TLBREHI_PS ((UINTN)(0x3f) << CSR_TLBREHI_PS_SHIFT)
+
+#define EFI_MEMORY_CACHETYPE_MASK (EFI_MEMORY_UC | \
+ EFI_MEMORY_WC | \
+ EFI_MEMORY_WT | \
+ EFI_MEMORY_WB | \
+ EFI_MEMORY_UCE \
+ )
+
+
+typedef struct {
+ EFI_PHYSICAL_ADDRESS PhysicalBase;
+ EFI_VIRTUAL_ADDRESS VirtualBase;
+ UINTN Length;
+ UINTN Attributes;
+} MEMORY_REGION_DESCRIPTOR;
+
+// The total number of descriptors, including the final "end-of-table" descriptor.
+#define MAX_VIRTUAL_MEMORY_MAP_DESCRIPTORS (128)
+
+extern CHAR8 HandleTlbRefill[], HandleTlbRefillEnd[];
+#endif
diff --git a/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/page.h b/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/page.h
new file mode 100644
index 0000000000..3b3b0b72c3
--- /dev/null
+++ b/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/page.h
@@ -0,0 +1,267 @@
+/** @file
+
+ Copyright (c) 2021 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+ @par Glossary:
+ - Pgd or Pgd or PGD - Page Global Directory
+ - Pud or Pud or PUD - Page Upper Directory
+ - Pmd or Pmd or PMD - Page Middle Directory
+ - Pte or pte or PTE - Page Table Entry
+ - Val or VAL or val - Value
+ - Dir - Directory
+**/
+#ifndef PAGE_H_
+#define PAGE_H_
+
+#define MAX_VA_BITS 47
+#define PGD_WIDE (8)
+#define PUD_WIDE (9)
+#define PMD_WIDE (9)
+#define PTE_WIDE (9)
+
+#define ENTRYS_PER_PGD (1 << PGD_WIDE)
+#define ENTRYS_PER_PUD (1 << PUD_WIDE)
+#define ENTRYS_PER_PMD (1 << PMD_WIDE)
+#define ENTRYS_PER_PTE (1 << PTE_WIDE)
+
+#define PGD_SHIFT (PUD_SHIFT + PUD_WIDE)
+#define PUD_SHIFT (PMD_SHIFT + PMD_WIDE)
+#define PMD_SHIFT (EFI_PAGE_SHIFT + PTE_WIDE)
+#define PTE_SHIFT (EFI_PAGE_SHIFT)
+
+#define PGD_SIZE (1UL << PGD_SHIFT)
+#define PUD_SIZE (1UL << PUD_SHIFT)
+#define PMD_SIZE (1UL << PMD_SHIFT)
+
+#define PGD_MASK (~(PGD_SIZE-1))
+#define PUD_MASK (~(PUD_SIZE-1))
+#define PMD_MASK (~(PMD_SIZE-1))
+#define PAGE_MASK (~(EFI_PAGE_SIZE - 1))
+#define PFN_MASK (~(((UINTN)(1) << (EFI_PAGE_SHIFT)) - 1) & \
+ (((UINTN)(1) << (PAGE_PFN_END_SHIFT)) - 1))
+
+typedef struct { UINTN PgdVal; } PGD;
+typedef struct { UINTN PudVal; } PUD;
+typedef struct { UINTN PmdVal; } PMD;
+typedef struct { UINTN PteVal; } PTE;
+/**
+ Gets the value of the page global directory table entry.
+
+ @param x Page global directory struct variables.
+
+ @retval the value of the page global directory table entry.
+ **/
+#define PGD_VAL(x) ((x).PgdVal)
+/**
+ Gets the value of the page upper directory table entry.
+
+ @param x Page upper directory struct variables.
+
+ @retval the value of the page upper directory table entry.
+ **/
+#define PUD_VAL(x) ((x).PudVal)
+/**
+ Gets the value of the page middle directory table entry.
+
+ @param x Page middle directory struct variables.
+
+ @retval the value of the page middle directory table entry.
+ **/
+#define PMD_VAL(x) ((x).PmdVal)
+/**
+ Gets the value of the page table entry.
+
+ @param x Page table entry struct variables.
+
+ @retval the value of the page table entry.
+ **/
+#define PTE_VAL(x) ((x).PteVal)
+
+
+#define PGD_TABLE_SIZE (ENTRYS_PER_PGD * sizeof(PGD))
+#define PUD_TABLE_SIZE (ENTRYS_PER_PUD * sizeof(PUD))
+#define PMD_TABLE_SIZE (ENTRYS_PER_PMD * sizeof(PMD))
+#define PTE_TABLE_SIZE (ENTRYS_PER_PTE * sizeof(PTE))
+/**
+ Gets the physical address of the record in the page table entry.
+
+ @param x Page table entry struct variables.
+
+ @retval the value of the physical address.
+ **/
+#define GET_PAGE_ATTRIBUTES(x) (UINTN) {(PTE_VAL(x) & ~PFN_MASK)}
+/**
+ Gets the virtual address of the next block of the specified virtual address
+ that is aligned with the size of the global page directory mapping.
+
+ @param Address Specifies the virtual address.
+ @param End The end address of the memory region.
+
+ @retval the specified virtual address of the next block.
+ **/
+#define PGD_ADDRESS_END(Address, End) \
+({ UINTN Boundary = ((Address) + PGD_SIZE) & PGD_MASK; \
+ (Boundary - 1 < (End) - 1)? Boundary: (End); \
+})
+/**
+ Gets the virtual address of the next block of the specified virtual address
+ that is aligned with the size of the page upper directory mapping.
+
+ @param Address Specifies the virtual address.
+ @param End The end address of the memory region.
+
+ @retval the specified virtual address of the next block.
+ **/
+#define PUD_ADDRESS_END(Address, End) \
+({ UINTN Boundary = ((Address) + PUD_SIZE) & PUD_MASK; \
+ (Boundary - 1 < (End) - 1)? Boundary: (End); \
+})
+/**
+ Gets the virtual address of the next block of the specified virtual address
+ that is aligned with the size of the page middle directory mapping.
+
+ @param Address Specifies the virtual address.
+ @param End The end address of the memory region.
+
+ @retval the specified virtual address of the next block.
+ **/
+#define PMD_ADDRESS_END(Address, End) \
+({ UINTN Boundary = ((Address) + PMD_SIZE) & PMD_MASK; \
+ (Boundary - 1 < (End) - 1)? Boundary: (End); \
+})
+/**
+ Get Specifies the virtual address corresponding to the index of the page global directory table entry.
+
+ @param Address Specifies the virtual address.
+
+ @retval the index of the page global directory table entry.
+ **/
+#define PGD_INDEX(Address) (((Address) >> PGD_SHIFT) & (ENTRYS_PER_PGD-1))
+/**
+ Get Specifies the virtual address corresponding to the index of the page upper directory table entry.
+
+ @param Address Specifies the virtual address.
+ @param End The end address of the memory region.
+
+ @retval the index of the page upper directory table entry.
+ **/
+#define PUD_INDEX(Address) (((Address) >> PUD_SHIFT) & (ENTRYS_PER_PUD - 1))
+/**
+ Get Specifies the virtual address corresponding to the index of the page middle directory table entry.
+
+ @param Address Specifies the virtual address.
+
+ @retval the index of the page middle directory table entry.
+ **/
+#define PMD_INDEX(Address) (((Address) >> PMD_SHIFT) & (ENTRYS_PER_PMD - 1))
+/**
+ Get Specifies the virtual address corresponding to the index of the page table entry.
+
+ @param Address Specifies the virtual address.
+
+ @retval the index of the page table entry.
+ **/
+#define PTE_INDEX(Address) (((Address) >> EFI_PAGE_SHIFT) & (ENTRYS_PER_PTE - 1))
+
+/**
+ Calculates the value of the page table entry based on the specified virtual address and properties.
+
+ @param Address Specifies the virtual address.
+ @param Attributes Specifies the Attributes.
+
+ @retval the value of the page table entry.
+ **/
+#define MAKE_PTE(Address, Attributes) (PTE){((((Address) >> EFI_PAGE_SHIFT) << 12) | (Attributes))}
+/**
+ Calculates the value of the Huge page table entry based on the specified virtual address and properties.
+
+ @param Address Specifies the virtual address.
+ @param Attributes Specifies the Attributes.
+
+ @retval the value of the HUGE page table entry.
+ **/
+#define MAKE_HUGE_PTE(Address, Attributes) (((((Address) >> PMD_SHIFT) << PMD_SHIFT) | ((Attributes) | PAGE_HUGE)))
+ /**
+ Check whether the large page table entry is.
+
+ @param Val The value of the page table entry.
+
+ @retval 1 Is huge page table entry.
+ @retval 0 Isn't huge page table entry.
+ **/
+#define IS_HUGE_PAGE(Val) (((Val) & PAGE_HUGE) == PAGE_HUGE)
+#define HUGE_PAGE_SIZE (PMD_SIZE)
+
+ /**
+ Check that the global page directory table entry is empty.
+
+ @param pgd the global page directory struct variables.
+
+ @retval 1 Is huge page table entry.
+ @retval 0 Isn't huge page table entry.
+ **/
+STATIC
+inline
+UINTN
+pgd_none (
+ IN PGD pgd
+ )
+{
+ return (PGD_VAL(pgd) == (UINTN)PcdGet64(PcdInvalidPud));
+}
+
+ /**
+ Check that the page upper directory table entry is empty.
+
+ @param pud Page upper directory struct variables.
+
+ @retval 1 Is huge page table entry.
+ @retval 0 Isn't huge page table entry.
+ **/
+STATIC
+inline
+UINTN
+pud_none (
+ IN PUD pud
+ )
+{
+ return (PUD_VAL(pud) == (UINTN)PcdGet64 (PcdInvalidPmd));
+}
+
+ /**
+ Check that the page middle directory table entry is empty.
+
+ @param pmd Page middle directory struct variables.
+
+ @retval 1 Is huge page table entry.
+ @retval 0 Isn't huge page table entry.
+ **/
+STATIC
+inline
+UINTN
+pmd_none (
+ IN PMD pmd
+ )
+{
+ return (PMD_VAL(pmd) == (UINTN)PcdGet64(PcdInvalidPte));
+}
+ /**
+ Check that the page table entry is empty.
+
+ @param pmd Page table entry struct variables.
+
+ @retval 1 Is huge page table entry.
+ @retval 0 Isn't huge page table entry.
+ **/
+STATIC
+inline
+UINTN
+pte_none (
+ IN PTE pte
+ )
+{
+ return (!(PTE_VAL(pte) & (~PAGE_GLOBAL)));
PAGE_VALID represents the tlb is valid, PAGE_GLOBAL represents tlb entry is valid for all asid processes.
how about using PAGE_VALID bit rather than PAGE_GLOBAL:
return (!(PTE_VAL(pte) & PAGE_VALID));


+}
+#endif
diff --git a/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/pte.h b/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/pte.h
new file mode 100644
index 0000000000..d6ac74f9c9
--- /dev/null
+++ b/Platform/Loongson/LoongArchQemuPkg/Library/MmuLib/pte.h
@@ -0,0 +1,57 @@
+/** @file
+
+ Copyright (c) 2021 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+ @par Glossary:
+ - Tlb or TLB - Translation Lookaside Buffer
+ - HGLOBAL - Huge Global
+ - PFN - Page Frame number
+ - EXEC - Execute
+ - PLV - Privilege Level
+ - RPLV - Restricted Privilege Level
+ - SUC - Strong-ordered UnCached
+ - CC - Coherent Cached
+ - WUC - Weak-ordered UnCached
+**/
+#ifndef PTE_H_
+#define PTE_H_
+/*Page table property definitions */
+#define PAGE_VALID_SHIFT 0
+#define PAGE_DIRTY_SHIFT 1
+#define PAGE_PLV_SHIFT 2 /* 2~3, two bits */
+#define CACHE_SHIFT 4 /* 4~5, two bits */
+#define PAGE_GLOBAL_SHIFT 6
+#define PAGE_HUGE_SHIFT 6 /* HUGE is a PMD bit */
+
+#define PAGE_HGLOBAL_SHIFT 12 /* HGlobal is a PMD bit */
+#define PAGE_PFN_SHIFT 12
+#define PAGE_PFN_END_SHIFT 48
+#define PAGE_NO_READ_SHIFT 61
+#define PAGE_NO_EXEC_SHIFT 62
+#define PAGE_RPLV_SHIFT 63
+
+/* Used by TLB hardware (placed in EntryLo*) */
+#define PAGE_VALID ((UINTN)(1) << PAGE_VALID_SHIFT)
+#define PAGE_DIRTY ((UINTN)(1) << PAGE_DIRTY_SHIFT)
+#define PAGE_PLV ((UINTN)(3) << PAGE_PLV_SHIFT)
+#define PAGE_GLOBAL ((UINTN)(1) << PAGE_GLOBAL_SHIFT)
+#define PAGE_HUGE ((UINTN)(1) << PAGE_HUGE_SHIFT)
+#define PAGE_HGLOBAL ((UINTN)(1) << PAGE_HGLOBAL_SHIFT)
+#define PAGE_NO_READ ((UINTN)(1) << PAGE_NO_READ_SHIFT)
+#define PAGE_NO_EXEC ((UINTN)(1) << PAGE_NO_EXEC_SHIFT)
+#define PAGE_RPLV ((UINTN)(1) << PAGE_RPLV_SHIFT)
+#define CACHE_MASK ((UINTN)(3) << CACHE_SHIFT)
+#define PFN_SHIFT (EFI_PAGE_SHIFT - 12 + PAGE_PFN_SHIFT)
+
+#define PLV_KERNEL 0
+#define PLV_USER 3
+
+#define PAGE_USER (PLV_USER << PAGE_PLV_SHIFT)
+#define PAGE_KERNEL (PLV_KERN << PAGE_PLV_SHIFT)
+
+#define CACHE_SUC (0 << CACHE_SHIFT) /* Strong-ordered UnCached */
+#define CACHE_CC (1 << CACHE_SHIFT) /* Coherent Cached */
+#define CACHE_WUC (2 << CACHE_SHIFT) /* Weak-ordered UnCached */
+#endif


[PATCH] RedfishPkg/RedfishDiscoverDxe: Fix memory free issue

Chang, Abner
 

From: Abner Chang <abner.chang@...>

Check the memory block pointer before freeing it.

Cc: Nickle Wang <nickle@...>
Cc: Igor Kulchytskyy <igork@...>
Signed-off-by: Abner Chang <abner.chang@...>
---
.../RedfishDiscoverDxe/RedfishDiscoverDxe.c | 16 ++++++++++------
1 file changed, 10 insertions(+), 6 deletions(-)

diff --git a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c
index 1293ddd633c..1616b5134bc 100644
--- a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c
+++ b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c
@@ -261,6 +261,7 @@ Tcp6GetSubnetInfo (

Tcp6 = (EFI_TCP6_PROTOCOL *)Instance->NetworkInterfaceProtocolInfo.NetworkProtocolInterface;

+ ZeroMem ((VOID *)&IpModedata, sizeof (EFI_IP6_MODE_DATA));
Status = Tcp6->GetModeData (Tcp6, NULL, NULL, &IpModedata, NULL, NULL);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "%a: Can't get IP mode data information\n", __FUNCTION__));
@@ -282,12 +283,15 @@ Tcp6GetSubnetInfo (
}

Instance->SubnetAddrInfoIPv6Number = IpModedata.AddressCount;
- CopyMem (
- (VOID *)Instance->SubnetAddrInfoIPv6,
- (VOID *)&IpModedata.AddressList,
- IpModedata.AddressCount * sizeof (EFI_IP6_ADDRESS_INFO)
- );
- FreePool (IpModedata.AddressList);
+ if (IpModedata.AddressCount != 0 && IpModedata.AddressList != NULL) {
+ CopyMem (
+ (VOID *)Instance->SubnetAddrInfoIPv6,
+ (VOID *)&IpModedata.AddressList,
+ IpModedata.AddressCount * sizeof (EFI_IP6_ADDRESS_INFO)
+ );
+ FreePool(IpModedata.AddressList);
+ }
+
return EFI_SUCCESS;
}

--
2.37.1.windows.1


Re: [edk2-CCodingStandardsSpecification] Create release/2.30 branch

Chang, Abner
 

[AMD Official Use Only - General]

Hi Mike,
Below are the tickets pulled out from BZ, is there any one you think is not necessary now?
Abner

713 EDK2 Document michael.d.kinney@... CONF --- Update EDK II C Coding standard to state a stronger preference for 80 column line widths 2021-07-27
1766 EDK2 Document michael.d.kinney@... CONF --- Remove use of STATIC macros from EDK II C Coding Standard Specification 2020-12-09
1698 EDK2 Document michael.d.kinney@... CONF --- Spurious rule about comment style in CCS 6.2.3 2021-07-27
714 EDK2 Document michael.d.kinney@... CONF --- Update EDK II C Coding Standards to allow multiple arguments per line in a function call 2021-07-27
4120 EDK2 Document abner.chang@... CONF --- File/Directory naming guidance for processor archs/vendors Tue 21:39
2664 EDK2 Document michael.d.kinney@... CONF --- Discrepancies/inconsistencies in coding standards, style and examples 2021-10-02

-----Original Message-----
From: Kinney, Michael D <michael.d.kinney@...>
Sent: Friday, October 28, 2022 11:22 PM
To: devel@edk2.groups.io; Chang, Abner <Abner.Chang@...>; Kinney,
Michael D <michael.d.kinney@...>
Subject: RE: [edk2-devel] [edk2-CCodingStandardsSpecification] Create
release/2.30 branch

Caution: This message originated from an External Source. Use proper caution
when opening attachments, clicking links, or responding.


Hi Abner,

Have you reviewed the open BZs against the EDK II C Coding Standard.

Are there any other issues that are considered important to fix before making a
new official release?

Thanks,

Mike

-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Chang,
Abner via groups.io
Sent: Thursday, October 27, 2022 9:54 AM
To: devel@edk2.groups.io
Cc: Abner Chang <abner.chang@...>
Subject: [edk2-devel] [edk2-CCodingStandardsSpecification] Create
release/2.30 branch

Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Abner Chang <abner.chang@...>
---
book.json | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/book.json b/book.json
index d112b26..1fdd570 100644
--- a/book.json
+++ b/book.json
@@ -1,8 +1,7 @@
{

"variables" : {

- "draft" : "yes",

"title" : "EDK II C Coding Standards Specification",

- "version" : "Revision 2.2"

+ "version" : "Revision 2.3"

},

"plugins": ["puml-aleung"],

"pluginsConfig": {}

--
2.37.1.windows.1





Re: [edk2-platforms][PATCH V4 01/14] Platform/Loongson: Add Serial Port library

maobibo
 

Hi xianglai,

I reply inline.

在 2022/10/21 15:11, xianglai li 写道:
Serial Port library for LoongarchQemuPkg

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

Signed-off-by: xianglai li <lixianglai@...>
---
.../LoongArchQemuPkg/Include/Library/Cpu.h | 387 +++++++++++
.../Include/LoongArchQemuPlatform.h | 97 +++
.../Library/SerialPortLib/SerialPortLib.c | 612 ++++++++++++++++++
.../Library/SerialPortLib/SerialPortLib.inf | 36 ++
4 files changed, 1132 insertions(+)
create mode 100644 Platform/Loongson/LoongArchQemuPkg/Include/Library/Cpu.h
create mode 100644 Platform/Loongson/LoongArchQemuPkg/Include/LoongArchQemuPlatform.h
create mode 100644 Platform/Loongson/LoongArchQemuPkg/Library/SerialPortLib/SerialPortLib.c
create mode 100644 Platform/Loongson/LoongArchQemuPkg/Library/SerialPortLib/SerialPortLib.inf

diff --git a/Platform/Loongson/LoongArchQemuPkg/Include/Library/Cpu.h b/Platform/Loongson/LoongArchQemuPkg/Include/Library/Cpu.h
new file mode 100644
index 0000000000..8c3c21bd96
--- /dev/null
+++ b/Platform/Loongson/LoongArchQemuPkg/Include/Library/Cpu.h
@@ -0,0 +1,387 @@
+/** @file
+
+ Copyright (c) 2021 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+ @par Glossary:
+ - EXC - Exception
+ - INT - Interrupt
+ - FPU - Floating Point Unit
+ - CSR - CPU Status Register
+ - READQ - Read Quad Word
+**/
+#ifndef LOONGARCH_CPU_H_
+#define LOONGARCH_CPU_H_
+
+/* Exception types decoded by machdep exception decoder */
+#define EXC_INT 0 /* HW interrupt */
+#define EXC_TLBL 1 /* TLB miss on a load */
+#define EXC_TLBS 2 /* TLB miss on a store */
+#define EXC_TLBI 3 /* TLB miss on a ifetch */
+#define EXC_TLBM 4 /* TLB modified fault */
+#define EXC_TLBRI 5 /* TLB Read-Inhibit exception */
+#define EXC_TLBXI 6 /* TLB Execution-Inhibit exception */
+#define EXC_TLBPE 7 /* TLB Privilege Error */
+#define EXC_ADE 8 /* Address Error */
+#define EXC_ALE 9 /* Unalign Access */
+#define EXC_OOB 10 /* Out of bounds */
+#define EXC_SYS 11 /* System call */
+#define EXC_BP 12 /* Breakpoint */
+#define EXC_INE 13 /* Inst. Not Exist */
+#define EXC_IPE 14 /* Inst. Privileged Error */
+#define EXC_FPDIS 15 /* FPU Disabled */
+#define EXC_LSXDIS 16 /* LSX Disabled */
+#define EXC_LASXDIS 17 /* LASX Disabled */
+#define EXC_FPE 18 /* Floating Point Exception */
+#define EXC_WATCH 19 /* Watch address reference */
+#define EXC_BAD 255 /* Undecodeable */
+
+#define COPY_SIGCODE // copy sigcode above user stack in exec
+#define ZERO $r0 /* wired zero */
+#define RA $r1 /* return address */
+#define GP $r2 /* global pointer - caller saved for PIC */
+#define SP $r3 /* stack pointer */
+#define V0 $r4 /* return value - caller saved */
+#define V1 $r5
+#define A0 $r4 /* argument registers */
+#define A1 $r5
+#define A2 $r6
+#define A3 $r7
+#define A4 $r8 /* arg reg 64 bit; caller saved in 32 bit */
+#define A5 $r9
+#define A6 $r10
+#define A7 $r11
+#define T0 $r12 /* caller saved */
+#define T1 $r13
+#define T2 $r14
+#define T3 $r15
+#define T4 $r16 /* callee saved */
+#define T5 $r17
+#define T6 $r18
+#define T7 $r19
+#define T8 $r20 /* caller saved */
+#define TP $r21 /* TLS */
+#define FP $r22 /* frame pointer */
+#define S0 $r23 /* callee saved */
+#define S1 $r24
+#define S2 $r25
+#define S3 $r26
+#define S4 $r27
+#define S5 $r28
+#define S6 $r29
+#define S7 $r30
+#define S8 $r31 /* callee saved */
+
+#define FCSR0 $r0
+
+//
+// Location of the saved registers relative to ZERO.
+// Usage is p->p_regs[XX].
+//
+#define RA_NUM 1
+#define GP_NUM 2
+#define SP_NUM 3
+#define A0_NUM 4
+#define A1_NUM 5
+#define A2_NUM 6
+#define A3_NUM 7
+#define A4_NUM 8
+#define A5_NUM 9
+#define A6_NUM 10
+#define A7_NUM 11
+#define T0_NUM 12
+#define T1_NUM 13
+#define T2_NUM 14
+#define T3_NUM 15
+#define T4_NUM 16
+#define T5_NUM 17
+#define T6_NUM 18
+#define T7_NUM 19
+#define T8_NUM 20
+#define TP_NUM 21
+#define FP_NUM 22
+#define S0_NUM 23
+#define S1_NUM 24
+#define S2_NUM 25
+#define S3_NUM 26
+#define S4_NUM 27
+#define S5_NUM 28
+#define S6_NUM 29
+#define S7_NUM 30
+#define S8_NUM 31
+
+#define FP0_NUM 0
+#define FP1_NUM 1
+#define FP2_NUM 2
+#define FP3_NUM 3
+#define FP4_NUM 4
+#define FP5_NUM 5
+#define FP6_NUM 6
+#define FP7_NUM 7
+#define FP8_NUM 8
+#define FP9_NUM 9
+#define FP10_NUM 10
+#define FP11_NUM 11
+#define FP12_NUM 12
+#define FP13_NUM 13
+#define FP14_NUM 14
+#define FP15_NUM 15
+#define FP16_NUM 16
+#define FP17_NUM 17
+#define FP18_NUM 18
+#define FP19_NUM 19
+#define FP20_NUM 20
+#define FP21_NUM 21
+#define FP22_NUM 22
+#define FP23_NUM 23
+#define FP24_NUM 24
+#define FP25_NUM 25
+#define FP26_NUM 26
+#define FP27_NUM 27
+#define FP28_NUM 28
+#define FP29_NUM 29
+#define FP30_NUM 30
+#define FP31_NUM 31
+#define FCSR_NUM 32
+#define FCC_NUM 33
+
+#ifdef __ASSEMBLY__
+#define _ULCAST_
+#define _U64CAST_
+#else
+#define _ULCAST_ (unsigned long)
+#define _U64CAST_ (u64)
+#endif
+
+#define LOONGARCH_CSR_CRMD 0
+#define LOONGARCH_CSR_PRMD 1
+#define LOONGARCH_CSR_EUEN 2
+#define CSR_EUEN_LBTEN_SHIFT 3
+#define CSR_EUEN_LBTEN (_ULCAST_(0x1) << CSR_EUEN_LBTEN_SHIFT)
+#define CSR_EUEN_LASXEN_SHIFT 2
+#define CSR_EUEN_LASXEN (_ULCAST_(0x1) << CSR_EUEN_LASXEN_SHIFT)
+#define CSR_EUEN_LSXEN_SHIFT 1
+#define CSR_EUEN_LSXEN (_ULCAST_(0x1) << CSR_EUEN_LSXEN_SHIFT)
+#define CSR_EUEN_FPEN_SHIFT 0
+#define CSR_EUEN_FPEN (_ULCAST_(0x1) << CSR_EUEN_FPEN_SHIFT)
+#define LOONGARCH_CSR_ECFG 4
+
+/* Exception status */
+#define LOONGARCH_CSR_ESTAT 5
+#define CSR_ESTAT_ESUBCODE_SHIFT 22
+#define CSR_ESTAT_ESUBCODE_WIDTH 9
+#define CSR_ESTAT_ESUBCODE (_ULCAST_(0x1ff) << CSR_ESTAT_ESUBCODE_SHIFT)
+#define CSR_ESTAT_EXC_SHIFT 16
+#define CSR_ESTAT_EXC_WIDTH 6
+#define CSR_ESTAT_EXC (_ULCAST_(0x3f) << CSR_ESTAT_EXC_SHIFT)
+#define CSR_ESTAT_IS_SHIFT 0
+#define CSR_ESTAT_IS_WIDTH 15
+#define CSR_ESTAT_IS (_ULCAST_(0x7fff) << CSR_ESTAT_IS_SHIFT)
+
+#define LOONGARCH_CSR_EPC 6
+#define LOONGARCH_CSR_BADV 7
+#define LOONGARCH_CSR_BADINST 8
+#define LOONGARCH_CSR_BADI 8
+#define LOONGARCH_CSR_EBASE 0xc /* Exception entry base address */
+#define LOONGARCH_CSR_CPUNUM 0x20 /* CPU core number */
+
+/* register number save in stack on exception */
+#define FP_BASE_NUM 34
+#define BASE_NUM 32
+#define CSR_NUM 10
+#define FP_BASE_INDEX (CSR_NUM + BASE_NUM)
+#define BOOTCORE_ID 0
+
+#define LOONGSON_IOCSR_IPI_STATUS 0x1000
+#define LOONGSON_IOCSR_IPI_EN 0x1004
+#define LOONGSON_IOCSR_IPI_SET 0x1008
+#define LOONGSON_IOCSR_IPI_CLEAR 0x100c
+#define LOONGSON_CSR_MAIL_BUF0 0x1020
+#define LOONGSON_CSR_MAIL_BUF1 0x1028
+#define LOONGSON_CSR_MAIL_BUF2 0x1030
+#define LOONGSON_CSR_MAIL_BUF3 0x1038
+
+/* Bit Domains for CFG registers */
+#define LOONGARCH_CPUCFG4 0x4
+#define LOONGARCH_CPUCFG5 0x5
+
+/* Kscratch registers */
+#define LOONGARCH_CSR_KS0 0x30
+#define LOONGARCH_CSR_KS1 0x31
+
+/* Stable timer registers */
+#define LOONGARCH_CSR_TMCFG 0x41
+#define LOONGARCH_CSR_TMCFG_EN (1ULL << 0)
+#define LOONGARCH_CSR_TMCFG_PERIOD (1ULL << 1)
+#define LOONGARCH_CSR_TMCFG_TIMEVAL (0x3fffffffffffULL << 2)
+#define LOONGARCH_CSR_TVAL 0x42 /* Timer value */
+#define LOONGARCH_CSR_CNTC 0x43 /* Timer offset */
+#define LOONGARCH_CSR_TINTCLR 0x44 /* Timer interrupt clear */
+
+/* TLB refill exception base address */
+#define LOONGARCH_CSR_TLBREBASE 0x88
+#define LOONGARCH_CSR_TLBRSAVE 0x8b /* KScratch for TLB refill exception */
+#define LOONGARCH_CSR_PGD 0x1b /* Page table base */
+
+/* Bits 8 and 9 of FPU Status Register specify the rounding mode */
+#define FPU_CSR_RM 0x300
+#define FPU_CSR_RN 0x000 /* nearest */
+#define FPU_CSR_RZ 0x100 /* towards zero */
+#define FPU_CSR_RU 0x200 /* towards +Infinity */
+#define FPU_CSR_RD 0x300 /* towards -Infinity */
+
+/*
+ Reads data from the specified CSR register.
+
+ @param[OUT] val The value is read from the CSR specified register.
+ @param[IN] reg Specifies the register number of the CSR to read the data.
+
+ @retval VOID
+ */
+#ifdef __GNUC__
+#define LOONGARCH_CSR_READQ(val, reg) \
+do { \
+ UINT64 __res; \
+ /* csrrd rd, csr_num */ \
+ __asm__ __volatile__( \
+ "csrrd %0, %1 \n\t" \
+ :"=r"(__res) \
+ :"i"(reg) \
+ : \
+ ); \
+ (val) = __res; \
+} while(0)
+#endif
+
+/*
+ Write data to the specified CSR register.
+
+ @param[OUT] val The value is write to the CSR specified register.
+ @param[IN] reg Specifies the register number of the CSR to write the data.
+
+ @retval VOID
+ */
+#ifdef __GNUC__
+#define LOONGARCH_CSR_WRITEQ(val, reg) \
+do { \
+ UINT64 __val = val; \
+ /* csrwr rd, csr_num */ \
+ __asm__ __volatile__( \
+ "csrwr %0, %1 \n\t" \
+ : "+r"(__val) \
+ : "i"(reg), "r"(__val) \
+ : "memory" \
+ ); \
+} while(0)
+#endif
+
+/*
+ Exchange specified bit data with the specified CSR registers
+
+ @param[IN] val The value Exchanged with the CSR specified register.
+ @param[IN] mask Specifies the mask for swapping bits
+ @param[IN] reg Specifies the register number of the CSR to Exchange the data.
+
+ @retval VOID
+ */
+#ifdef __GNUC__
+#define LOONGARCH_CSR_XCHGQ(val, mask, reg) \
+do { \
+ UINT64 __val = val; \
+ UINT64 __mask = mask; \
+ /* csrwr rd, csr_num */ \
+ __asm__ __volatile__( \
+ "csrxchg %0, %1, %2 \n\t" \
+ : "+r"(__val) \
+ : "r"(__mask), "i"(reg), "r"(__val) \
+ : "memory" \
+ ); \
+} while(0)
+#endif
+
+/*
+ Search for tlb
+
+ @param VOID
+
+ @retval VOID
+ */
+#ifdef __GNUC__
+#define LOONGARCH_TLB_SRCH() \
+do { \
+ /* tlbsrch */ \
+ __asm__ __volatile__( \
+ "tlbsrch" \
+ ); \
+} while(0)
+#endif
+
+/*
+ Writes data to the specified tlb table entry.
+
+ @param VOID
+
+ @retval VOID
+ */
+#ifdef __GNUC__
+#define LOONGARCH_TLB_WR() \
+do { \
+ /* tlbwr */ \
+ __asm__ __volatile__( \
+ "tlbwr" \
+ ); \
+} while(0)
+#endif
+/*
+ Reads data from the specified CPUCFG register.
+
+ @param[OUT] val The value is read from the CPUCFG specified register.
+ @param[IN] reg Specifies the register number of the CPUCFG to read the data.
+
+ @retval VOID
+ */
+#ifdef __GNUC__
+#define LOONGARCH_GET_CPUCFG(val, reg) \
+do { \
+ UINT64 __res; \
+ /* cpucfg rd, rj */ \
+ __asm__ __volatile__( \
+ "cpucfg %0, %1 \n\t" \
+ :"=r"(__res) \
+ :"r"(reg) \
+ : \
+ ); \
+ val = (UINT32)__res; \
+} while(0)
+#endif
+
+/*
+ Enables floating-point unit
+
+ @param VOID
+
+ @retval VOID
+ */
+#define LOONGARCH_ENABLR_FPU() \
+do { \
+ LOONGARCH_CSR_XCHGQ(CSR_EUEN_FPEN, \
+ CSR_EUEN_FPEN, \
+ LOONGARCH_CSR_EUEN); \
+} while (0)
+
+/*
+ Disable floating-point unit
+
+ @param VOID
+
+ @retval VOID
+ */
+#define LOONGARCH_DISABLE_FPU() \
+do { \
+ LOONGARCH_CSR_XCHGQ(0, \
+ CSR_EUEN_FPEN, \
+ LOONGARCH_CSR_EUEN); \
+} while (0)
Can we remove these inline assemble language lines and put it in ASM code?

regards
bibo, mao
+
+#endif
diff --git a/Platform/Loongson/LoongArchQemuPkg/Include/LoongArchQemuPlatform.h b/Platform/Loongson/LoongArchQemuPkg/Include/LoongArchQemuPlatform.h
new file mode 100644
index 0000000000..ed672844b4
--- /dev/null
+++ b/Platform/Loongson/LoongArchQemuPkg/Include/LoongArchQemuPlatform.h
@@ -0,0 +1,97 @@
+/** @file
+ LoongArch Qemu Platform macro definition.
+
+ Copyright (c) 2021, Loongson Limited. All rights reserved.
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+ **/
+
+#ifndef LOONGARCH_QEMU_PLATFORM_H_
+#define LOONGARCH_QEMU_PLATFORM_H_
+
+
+/* Acpi pm device */
+#define LS7A_PCH_REG_BASE 0x10000000UL
+#define LS7A_ACPI_REG_BASE (LS7A_PCH_REG_BASE + 0x000D0000)
+#define LS7A_PM_CNT_BLK (0x14) /* 2 bytes */
+#define LS7A_GPE0_RESET_REG (0x30) /* 4 bytes */
+
+#define ACPI_BITMASK_SLEEP_TYPE 0x1C00
+#define ACPI_BITMASK_SLEEP_ENABLE 0x2000
+
+
+//---------------------------------------------
+// UART Register Offsets
+//---------------------------------------------
+#define BAUD_LOW_OFFSET 0x00
+#define BAUD_HIGH_OFFSET 0x01
+#define IER_OFFSET 0x01
+#define LCR_SHADOW_OFFSET 0x01
+#define FCR_SHADOW_OFFSET 0x02
+#define IR_CONTROL_OFFSET 0x02
+#define FCR_OFFSET 0x02
+#define EIR_OFFSET 0x02
+#define BSR_OFFSET 0x03
+#define LCR_OFFSET 0x03
+#define MCR_OFFSET 0x04
+#define LSR_OFFSET 0x05
+#define MSR_OFFSET 0x06
+
+/* character format control register */
+#define CFCR_DLAB 0x80 /* divisor latch */
+#define CFCR_SBREAK 0x40 /* send break */
+#define CFCR_PZERO 0x30 /* zero parity */
+#define CFCR_PONE 0x20 /* one parity */
+#define CFCR_PEVEN 0x10 /* even parity */
+#define CFCR_PODD 0x00 /* odd parity */
+#define CFCR_PENAB 0x08 /* parity enable */
+#define CFCR_STOPB 0x04 /* 2 stop bits */
+#define CFCR_8BITS 0x03 /* 8 data bits */
+#define CFCR_7BITS 0x02 /* 7 data bits */
+#define CFCR_6BITS 0x01 /* 6 data bits */
+#define CFCR_5BITS 0x00 /* 5 data bits */
+/* modem control register */
+#define MCR_LOOPBACK 0x10 /* loopback */
+#define MCR_IENABLE 0x08 /* output 2 = int enable */
+#define MCR_DRS 0x04 /* output 1 = xxx */
+#define MCR_RTS 0x02 /* enable RTS */
+#define MCR_DTR 0x01 /* enable DTR */
+
+/* line status register */
+#define LSR_RCV_FIFO 0x80 /* error in receive fifo */
+#define LSR_TSRE 0x40 /* transmitter empty */
+#define LSR_TXRDY 0x20 /* transmitter ready */
+#define LSR_BI 0x10 /* break detected */
+#define LSR_FE 0x08 /* framing error */
+#define LSR_PE 0x04 /* parity error */
+#define LSR_OE 0x02 /* overrun error */
+#define LSR_RXRDY 0x01 /* receiver ready */
+#define LSR_RCV_MASK 0x1f
+
+/* 16550 UART register offsets and bitfields */
+#define R_UART_RXBUF 0
+#define R_UART_TXBUF 0
+#define R_UART_BAUD_LOW 0
+#define R_UART_BAUD_HIGH 1
+#define R_UART_FCR 2
+#define B_UART_FCR_FIFOE BIT0
+#define B_UART_FCR_FIFO64 BIT5
+#define R_UART_LCR 3
+#define B_UART_LCR_DLAB BIT7
+#define R_UART_MCR 4
+#define B_UART_MCR_DTRC BIT0
+#define B_UART_MCR_RTS BIT1
+#define R_UART_LSR 5
+#define B_UART_LSR_RXRDY BIT0
+#define B_UART_LSR_TXRDY BIT5
+#define B_UART_LSR_TEMT BIT6
+#define R_UART_MSR 6
+#define B_UART_MSR_CTS BIT4
+#define B_UART_MSR_DSR BIT5
+#define B_UART_MSR_RI BIT6
+#define B_UART_MSR_DCD BIT7
+#define UART_BASE_ADDRESS (0x1fe001e0)
+#define UART_BPS (115200)
+#define UART_WAIT_TIMOUT (1000000)
+#endif
diff --git a/Platform/Loongson/LoongArchQemuPkg/Library/SerialPortLib/SerialPortLib.c b/Platform/Loongson/LoongArchQemuPkg/Library/SerialPortLib/SerialPortLib.c
new file mode 100644
index 0000000000..eb1ce17d69
--- /dev/null
+++ b/Platform/Loongson/LoongArchQemuPkg/Library/SerialPortLib/SerialPortLib.c
@@ -0,0 +1,612 @@
+/** @file
+ UART Serial Port library functions
+
+ Copyright (c) 2021 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+ @par Glossary:
+ - Bps - Bit Per Second
+ - CTL - Control
+ - Config - Configure
+**/
+
+#include <Base.h>
+#include <Library/Cpu.h>
+#include <Library/IoLib.h>
+#include <Library/SerialPortLib.h>
+#include <LoongArchQemuPlatform.h>
+
+UINTN gUartBase = UART_BASE_ADDRESS;
+UINTN gBps = UART_BPS;
+
+/**
+ Initialize the serial device hardware.
+
+ If no initialization is required, then return RETURN_SUCCESS.
+ If the serial device was successfuly initialized, then return RETURN_SUCCESS.
+ If the serial device could not be initialized, then return RETURN_DEVICE_ERROR.
+
+ @retval RETURN_SUCCESS The serial device was initialized.
+ @retval RETURN_DEVICE_ERROR The serail device could not be initialized.
+
+**/
+RETURN_STATUS
+EFIAPI
+SerialPortInitialize (
+ VOID
+ )
+{
+ UINTN TimeOut;
+ //
+ // wait for Tx fifo to completely drain */
+ //
+ TimeOut = UART_WAIT_TIMOUT;
+ while (!(MmioRead8 ((UINTN) gUartBase + LSR_OFFSET) & LSR_TSRE)) {
+ if (--TimeOut == 0) {
+ break;
+ }
+ }
+ //
+ // Set communications format
+ //
+ MmioWrite8 ((UINTN) (gUartBase + LCR_OFFSET), CFCR_DLAB);
+
+ //
+ // Configure baud rate
+ //
+
+
+ MmioWrite8 ((UINTN) (gUartBase + LCR_OFFSET), CFCR_8BITS);
+ MmioWrite8 ((UINTN) (gUartBase + MCR_OFFSET), MCR_IENABLE | MCR_DTR | MCR_RTS);
+ //
+ // if enable interrupt the kernel of lemote will error in STR mode during wake up phase.
+ //
+ //MmioWrite8 ((UINTN) (gUartBase + IER_OFFSET), CFCR_8BITS);
+
+ return RETURN_SUCCESS;
+}
+
+/**
+ Write data from buffer to serial device.
+
+ Writes NumberOfBytes data bytes from Buffer to the serial device.
+ The number of bytes actually written to the serial device is returned.
+ If the return value is less than NumberOfBytes, then the write operation failed.
+
+ If Buffer is NULL, then ASSERT ().
+
+ If NumberOfBytes is zero, then return 0.
+
+ @param Buffer Pointer to the data buffer to be written.
+ @param NumberOfBytes Number of bytes to written to the serial device.
+
+ @retval 0 NumberOfBytes is 0.
+ @retval >0 The number of bytes written to the serial device.
+ If this value is less than NumberOfBytes, then the read operation failed.
+
+**/
+UINTN
+EFIAPI
+UartCtlWrite (
+ IN UINT8 *Buffer,
+ IN UINTN NumberOfBytes,
+ IN UINTN CtlAddr
+)
+{
+ UINTN Result;
+ UINT8 Data;
+
+ if (Buffer == NULL) {
+ return 0;
+ }
+
+ Result = NumberOfBytes;
+
+ while (NumberOfBytes--) {
+ //
+ // Wait for the serail port to be ready.
+ //
+ do {
+ Data = MmioRead8 (CtlAddr + LSR_OFFSET);
+ } while ((Data & LSR_TXRDY) == 0);
+ MmioWrite8 (CtlAddr, *Buffer++);
+ }
+
+ return Result;
+}
+/**
+ Writes data to serial port.
+
+ @param Buffer Pointer to the data buffer to store the data writed to serial port.
+ @param NumberOfBytes Number of bytes to write to the serial port.
+
+ @retval 0 NumberOfBytes is 0.
+ @retval >0 The number of bytes write the serial port.
+ If this value is less than NumberOfBytes, then the write operation failed.
+
+**/
+UINTN
+EFIAPI
+SerialPortWrite (
+ IN UINT8 *Buffer,
+ IN UINTN NumberOfBytes
+)
+{
+ return UartCtlWrite (Buffer, NumberOfBytes, gUartBase);
+}
+/**
+ Reads data from a serial device into a buffer.
+
+ @param Buffer Pointer to the data buffer to store the data read from the serial device.
+ @param NumberOfBytes Number of bytes to read from the serial device.
+
+ @retval 0 NumberOfBytes is 0.
+ @retval >0 The number of bytes read from the serial device.
+ If this value is less than NumberOfBytes, then the read operation failed.
+
+**/
+UINTN
+EFIAPI
+UartCtlRead (
+ OUT UINT8 *Buffer,
+ IN UINTN NumberOfBytes,
+ IN UINTN CtlAddr
+)
+{
+ UINTN Result;
+ UINT8 Data;
+
+ if (NULL == Buffer) {
+ return 0;
+ }
+
+ Result = NumberOfBytes;
+
+ while (NumberOfBytes--) {
+ //
+ // Wait for the serail port to be ready.
+ //
+ do {
+ Data = MmioRead8 (CtlAddr + LSR_OFFSET);
+ } while ((Data & LSR_RXRDY) == 0);
+
+ *Buffer++ = MmioRead8 (CtlAddr);
+ }
+
+ return Result;
+}
+/**
+ Read data from serial port.
+
+ @param Buffer Pointer to the data buffer to store the data read from serial port.
+ @param NumberOfBytes Number of bytes to read from the serial port.
+
+ @retval 0 NumberOfBytes is 0.
+ @retval >0 The number of bytes read from the serial port.
+ If this value is less than NumberOfBytes, then the read operation failed.
+
+**/
+UINTN
+EFIAPI
+SerialPortRead (
+ OUT UINT8 *Buffer,
+ IN UINTN NumberOfBytes
+)
+{
+ return UartCtlRead (Buffer, NumberOfBytes, gUartBase);
+}
+/**
+ Polls a serial device to see if there is any data waiting to be read.
+
+ Polls aserial device to see if there is any data waiting to be read.
+ If there is data waiting to be read from the serial device, then TRUE is returned.
+ If there is no data waiting to be read from the serial device, then FALSE is returned.
+
+ @retval TRUE Data is waiting to be read from the serial device.
+ @retval FALSE There is no data waiting to be read from the serial device.
+
+**/
+BOOLEAN
+EFIAPI
+SerialPortPoll (
+ VOID
+ )
+{
+ UINT8 Data;
+
+ //
+ // Read the serial port status.
+ //
+ Data = MmioRead8 ((UINTN) gUartBase + LSR_OFFSET);
+
+ return (BOOLEAN) ((Data & LSR_RXRDY) != 0);
+}
+/**
+ To get serial register base address.
+
+ @param VOID
+
+ @return serial register base address.
+**/
+UINTN
+GetSerialRegisterBase (
+ VOID
+ )
+{
+ return gUartBase;
+}
+/**
+ Read an 8-bit register.
+ @param Base The base address register of UART device.
+ @param Offset The offset of the register to read.
+
+ @return The value read from the 16550 register.
+
+**/
+UINT8
+SerialPortReadRegister (
+ UINTN Base,
+ UINTN Offset
+ )
+{
+ return MmioRead8 (Base + Offset);
+}
+
+/**
+ Write an 8-bit register.
+ @param Base The base address register of UART device.
+ @param Offset The offset of the register to write.
+ @param Value The value to write to the register specified by Offset.
+
+ @return The value written to the 16550 register.
+
+**/
+UINT8
+SerialPortWriteRegister (
+ UINTN Base,
+ UINTN Offset,
+ UINT8 Value
+ )
+{
+ return MmioWrite8 (Base + Offset, Value);
+}
+
+/**
+ Sets the control bits on a serial device.
+
+ @param Control Sets the bits of Control that are settable.
+
+ @retval RETURN_SUCCESS The new control bits were set on the serial device.
+ @retval RETURN_UNSUPPORTED The serial device does not support this operation.
+ @retval RETURN_DEVICE_ERROR The serial device is not functioning correctly.
+
+**/
+RETURN_STATUS
+EFIAPI
+SerialPortSetControl (
+ IN UINT32 Control
+ )
+{
+ UINTN SerialRegisterBase;
+ UINT8 Mcr;
+
+ //
+ // First determine the parameter is invalid.
+ //
+ if ((Control & (~(EFI_SERIAL_REQUEST_TO_SEND | EFI_SERIAL_DATA_TERMINAL_READY |
+ EFI_SERIAL_HARDWARE_FLOW_CONTROL_ENABLE))) != 0)
+ {
+ return RETURN_UNSUPPORTED;
+ }
+
+ SerialRegisterBase = GetSerialRegisterBase ();
+ if (SerialRegisterBase ==0) {
+ return RETURN_UNSUPPORTED;
+ }
+
+ //
+ // Read the Modem Control Register.
+ //
+ Mcr = SerialPortReadRegister (SerialRegisterBase, R_UART_MCR);
+ Mcr &= (~(B_UART_MCR_DTRC | B_UART_MCR_RTS));
+
+ if ((Control & EFI_SERIAL_DATA_TERMINAL_READY) == EFI_SERIAL_DATA_TERMINAL_READY) {
+ Mcr |= B_UART_MCR_DTRC;
+ }
+
+ if ((Control & EFI_SERIAL_REQUEST_TO_SEND) == EFI_SERIAL_REQUEST_TO_SEND) {
+ Mcr |= B_UART_MCR_RTS;
+ }
+
+ //
+ // Write the Modem Control Register.
+ //
+ SerialPortWriteRegister (SerialRegisterBase, R_UART_MCR, Mcr);
+
+ return RETURN_SUCCESS;
+}
+
+/**
+ Retrieve the status of the control bits on a serial device.
+
+ @param Control A pointer to return the current control signals from the serial device.
+
+ @retval RETURN_SUCCESS The control bits were read from the serial device.
+ @retval RETURN_UNSUPPORTED The serial device does not support this operation.
+ @retval RETURN_DEVICE_ERROR The serial device is not functioning correctly.
+
+**/
+RETURN_STATUS
+EFIAPI
+SerialPortGetControl (
+ OUT UINT32 *Control
+ )
+{
+ UINTN SerialRegisterBase;
+ UINT8 Msr;
+ UINT8 Mcr;
+ UINT8 Lsr;
+
+ SerialRegisterBase = GetSerialRegisterBase ();
+ if (SerialRegisterBase ==0) {
+ return RETURN_UNSUPPORTED;
+ }
+
+ *Control = 0;
+
+ //
+ // Read the Modem Status Register.
+ //
+ Msr = SerialPortReadRegister (SerialRegisterBase, R_UART_MSR);
+
+ if ((Msr & B_UART_MSR_CTS) == B_UART_MSR_CTS) {
+ *Control |= EFI_SERIAL_CLEAR_TO_SEND;
+ }
+
+ if ((Msr & B_UART_MSR_DSR) == B_UART_MSR_DSR) {
+ *Control |= EFI_SERIAL_DATA_SET_READY;
+ }
+
+ if ((Msr & B_UART_MSR_RI) == B_UART_MSR_RI) {
+ *Control |= EFI_SERIAL_RING_INDICATE;
+ }
+
+ if ((Msr & B_UART_MSR_DCD) == B_UART_MSR_DCD) {
+ *Control |= EFI_SERIAL_CARRIER_DETECT;
+ }
+
+ //
+ // Read the Modem Control Register.
+ //
+ Mcr = SerialPortReadRegister (SerialRegisterBase, R_UART_MCR);
+
+ if ((Mcr & B_UART_MCR_DTRC) == B_UART_MCR_DTRC) {
+ *Control |= EFI_SERIAL_DATA_TERMINAL_READY;
+ }
+
+ if ((Mcr & B_UART_MCR_RTS) == B_UART_MCR_RTS) {
+ *Control |= EFI_SERIAL_REQUEST_TO_SEND;
+ }
+
+ if (PcdGetBool (PcdSerialUseHardwareFlowControl)) {
+ *Control |= EFI_SERIAL_HARDWARE_FLOW_CONTROL_ENABLE;
+ }
+
+ //
+ // Read the Line Status Register.
+ //
+ Lsr = SerialPortReadRegister (SerialRegisterBase, R_UART_LSR);
+
+ if ((Lsr & (B_UART_LSR_TEMT | B_UART_LSR_TXRDY)) == (B_UART_LSR_TEMT | B_UART_LSR_TXRDY)) {
+ *Control |= EFI_SERIAL_OUTPUT_BUFFER_EMPTY;
+ }
+
+ if ((Lsr & B_UART_LSR_RXRDY) == 0) {
+ *Control |= EFI_SERIAL_INPUT_BUFFER_EMPTY;
+ }
+
+ return RETURN_SUCCESS;
+}
+
+/**
+ Sets the baud rate, receive FIFO depth, transmit/receice time out, parity,
+ data bits, and stop bits on a serial device.
+
+ @param BaudRate The requested baud rate. A BaudRate value of 0 will use the
+ device's default interface speed.
+ On output, the value actually set.
+ @param ReveiveFifoDepth The requested depth of the FIFO on the receive side of the
+ serial interface. A ReceiveFifoDepth value of 0 will use
+ the device's default FIFO depth.
+ On output, the value actually set.
+ @param Timeout The requested time out for a single character in microseconds.
+ This timeout applies to both the transmit and receive side of the
+ interface. A Timeout value of 0 will use the device's default time
+ out value.
+ On output, the value actually set.
+ @param Parity The type of parity to use on this serial device. A Parity value of
+ DefaultParity will use the device's default parity value.
+ On output, the value actually set.
+ @param DataBits The number of data bits to use on the serial device. A DataBits
+ vaule of 0 will use the device's default data bit setting.
+ On output, the value actually set.
+ @param StopBits The number of stop bits to use on this serial device. A StopBits
+ value of DefaultStopBits will use the device's default number of
+ stop bits.
+ On output, the value actually set.
+
+ @retval RETURN_SUCCESS The new attributes were set on the serial device.
+ @retval RETURN_UNSUPPORTED The serial device does not support this operation.
+ @retval RETURN_INVALID_PARAMETER One or more of the attributes has an unsupported value.
+ @retval RETURN_DEVICE_ERROR The serial device is not functioning correctly.
+
+**/
+RETURN_STATUS
+EFIAPI
+UartCtlConfig (
+ IN OUT UINT64 *BaudRate,
+ IN OUT UINT32 *ReceiveFifoDepth,
+ IN OUT UINT32 *Timeout,
+ IN OUT EFI_PARITY_TYPE *Parity,
+ IN OUT UINT8 *DataBits,
+ IN OUT EFI_STOP_BITS_TYPE *StopBits,
+ IN UINTN CtlAddr
+ )
+{
+ UINTN SerialRegisterBase;
+ UINT8 Lcr;
+ UINT8 LcrData;
+ UINT8 LcrParity;
+ UINT8 LcrStop;
+
+
+ SerialRegisterBase = CtlAddr;
+ if (SerialRegisterBase ==0) {
+ return RETURN_UNSUPPORTED;
+ }
+
+ //
+ // Check for default settings and fill in actual values.
+ //
+ if (*BaudRate == 0) {
+ *BaudRate = PcdGet32 (PcdSerialBaudRate);
+ }
+
+ if (*DataBits == 0) {
+ LcrData = (UINT8) (PcdGet8 (PcdSerialLineControl) & 0x3);
+ *DataBits = LcrData + 5;
+ } else {
+ if ((*DataBits < 5)
+ || (*DataBits > 8))
+ {
+ return RETURN_INVALID_PARAMETER;
+ }
+ //
+ // Map 5..8 to 0..3
+ //
+ LcrData = (UINT8) (*DataBits - (UINT8) 5);
+ }
+
+ if (*Parity == DefaultParity) {
+ LcrParity = (UINT8) ((PcdGet8 (PcdSerialLineControl) >> 3) & 0x7);
+ switch (LcrParity) {
+ case 0:
+ *Parity = NoParity;
+ break;
+
+ case 3:
+ *Parity = EvenParity;
+ break;
+
+ case 1:
+ *Parity = OddParity;
+ break;
+
+ case 7:
+ *Parity = SpaceParity;
+ break;
+
+ case 5:
+ *Parity = MarkParity;
+ break;
+
+ default:
+ break;
+ }
+ } else {
+ switch (*Parity) {
+ case NoParity:
+ LcrParity = 0;
+ break;
+
+ case EvenParity:
+ LcrParity = 3;
+ break;
+
+ case OddParity:
+ LcrParity = 1;
+ break;
+
+ case SpaceParity:
+ LcrParity = 7;
+ break;
+
+ case MarkParity:
+ LcrParity = 5;
+ break;
+
+ default:
+ return RETURN_INVALID_PARAMETER;
+ }
+ }
+
+ if (*StopBits == DefaultStopBits) {
+ LcrStop = (UINT8) ((PcdGet8 (PcdSerialLineControl) >> 2) & 0x1);
+ switch (LcrStop) {
+ case 0:
+ *StopBits = OneStopBit;
+ break;
+
+ case 1:
+ if (*DataBits == 5) {
+ *StopBits = OneFiveStopBits;
+ } else {
+ *StopBits = TwoStopBits;
+ }
+ break;
+
+ default:
+ break;
+ }
+ } else {
+ switch (*StopBits) {
+ case OneStopBit:
+ LcrStop = 0;
+ break;
+
+ case OneFiveStopBits:
+ case TwoStopBits:
+ LcrStop = 1;
+ break;
+
+ default:
+ return RETURN_INVALID_PARAMETER;
+ }
+ }
+ SerialPortWriteRegister (SerialRegisterBase, R_UART_LCR, B_UART_LCR_DLAB);
+
+ //
+ // Clear DLAB and configure Data Bits, Parity, and Stop Bits.
+ // Strip reserved bits from line control value
+ //
+ Lcr = (UINT8) ((LcrParity << 3) | (LcrStop << 2) | LcrData);
+ SerialPortWriteRegister (SerialRegisterBase, R_UART_LCR, (UINT8) (Lcr & 0x3F));
+
+ return RETURN_SUCCESS;
+}
+/**
+ Set the serial port Attributes.
+
+ @param VOID
+
+ @return serial register base address.
+**/
+RETURN_STATUS
+EFIAPI
+SerialPortSetAttributes (
+ IN OUT UINT64 *BaudRate,
+ IN OUT UINT32 *ReceiveFifoDepth,
+ IN OUT UINT32 *Timeout,
+ IN OUT EFI_PARITY_TYPE *Parity,
+ IN OUT UINT8 *DataBits,
+ IN OUT EFI_STOP_BITS_TYPE *StopBits
+ )
+{
+ UINTN SerialRegisterBase;
+
+ SerialRegisterBase = GetSerialRegisterBase ();
+
+ return UartCtlConfig (&gBps, ReceiveFifoDepth, Timeout, Parity, DataBits, StopBits,
+ SerialRegisterBase);
+}
diff --git a/Platform/Loongson/LoongArchQemuPkg/Library/SerialPortLib/SerialPortLib.inf b/Platform/Loongson/LoongArchQemuPkg/Library/SerialPortLib/SerialPortLib.inf
new file mode 100644
index 0000000000..6c4674151b
--- /dev/null
+++ b/Platform/Loongson/LoongArchQemuPkg/Library/SerialPortLib/SerialPortLib.inf
@@ -0,0 +1,36 @@
+## @file
+# UART Serial Port library functions
+#
+# Copyright (c) 2021 Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = PcAtSerialPortLib
+ FILE_GUID = f4fb883d-8138-4f29-bb0c-c574e9312c74
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = SerialPortLib
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ Platform/Loongson/LoongArchQemuPkg/Loongson.dec
+
+[LibraryClasses]
+ BaseLib
+ IoLib
+ PcdLib
+
+[Sources]
+ SerialPortLib.c
+
+[Pcd]
+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialUseHardwareFlowControl ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialBaudRate ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialLineControl ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialClockRate ## CONSUMES


Re: [PATCH] RedfishPkg/RedfishPlatformCredentialLib: IPMI implementation

Nickle Wang
 

Hi Igor,

Yes, we should get the URI to computer system collection by parsing "/redfish/v1".

Hi Abner,

What do you think about this? And if we like to select authentication method for Redfish communication in this way, we need to update RedfishCredentialLib.h because now the authentication method is not decided by this low-level library.

Thanks,
Nickle


From: Igor Kulchytskyy <igork@...>
Sent: Saturday, October 29, 2022 12:03 AM
To: Nickle Wang <nicklew@...>; Chang, Abner <Abner.Chang@...>; devel@edk2.groups.io <devel@edk2.groups.io>
Cc: Nick Ramirez <nramirez@...>
Subject: RE: [EXTERNAL] RE: [edk2-devel] [PATCH] RedfishPkg/RedfishPlatformCredentialLib: IPMI implementation
 
External email: Use caution opening links or attachments


Hi Nickle,
I think this is a good idea to send a request to the URI which requires the authentication and then analyze the header of response.
The only thing I would like to discuss is a hardcoded URI - "/redfish/v1/Systems".
Shouldn't we parse "redfish/v1" json response and get the URI from "Systems" attribute.
That, I think, would be more universal method.
And that is what Redfish specification said, that user should be able to iterate from Redfish service root "redfish/v1" to any redfish resource.
Thank you,
Igor



-----Original Message-----
From: Nickle Wang <nicklew@...>
Sent: Friday, October 28, 2022 10:53 AM
To: Igor Kulchytskyy <igork@...>; Chang, Abner <Abner.Chang@...>; devel@edk2.groups.io
Cc: Nick Ramirez <nramirez@...>
Subject: RE: [EXTERNAL] RE: [edk2-devel] [PATCH] RedfishPkg/RedfishPlatformCredentialLib: IPMI implementation

Hi Igor, Abner,

Thanks for your comments. A quick summary as below:

- BIOS is not supported to disable bootstrap credential service. For security purposes, BIOS should shutdown credential service with its internal control mechanism.
- Credential libraries need a cache mechanism to prevent multiple queries to BMC. All applications in BIOS share the same credentials.
- The storage of keeping credentials should be deleted before the end of the DXE event. So that the credential will not be retrieved by unauthorized user or application. (e.g. user can read variable under UEFI shell with dmpstore command)

There is one thing remained and I like to have further discussion. For the authentication method, do we think that client user can decide what authentication method to use regardless of the requirement from server? I am thinking a detection mechanism as below:

Issue HTTP GET to "/redfish/v1/Systems" (which normally require authentication) without authentication method.
a) if client receive 200 OK, "No Auth" is used and we don't need to get credentials
b) if client receive 401 Unauthorized, check the "WWW-Authenticate" field in returned HTTP header. "Basic realm" or "X-Auh-Token realm" or both two methods will be specified. Then client can know what method to use. Two methods all require credential.

Above mechanism can be placed in RedfishCredentailDxe driver so driver will know if it needs to call credential lib or not.

Thanks,
Nickle

-----Original Message-----
From: Igor Kulchytskyy <igork@...>
Sent: Friday, October 28, 2022 9:54 PM
To: Chang, Abner <Abner.Chang@...>; devel@edk2.groups.io; Nickle Wang <nicklew@...>
Cc: Nick Ramirez <nramirez@...>
Subject: RE: [EXTERNAL] RE: [edk2-devel] [PATCH] RedfishPkg/RedfishPlatformCredentialLib: IPMI implementation

External email: Use caution opening links or attachments


Hi Abner,
Yes, you are right that NVRAM variables were deprecated by DMTF.
But we can use our own boot time NVRAM variable to keep FW credentials. That variable will not be accessible from OS, but since we agreed not to disable bootstrap credentials service on exit boot event, then OS may get its own credentials.
Or we can save the credentials in memory variable. But in this case if we have several instances of the library linked with different modules they will have to send their own IPMI command to get credentials.
So, I think it is better to use our own NVRAM boot time variable.
Thank you,
Igor


-----Original Message-----
From: Chang, Abner <Abner.Chang@...>
Sent: Friday, October 28, 2022 3:48 AM
To: devel@edk2.groups.io; Igor Kulchytskyy <igork@...>; nicklew@...
Cc: Nick Ramirez <nramirez@...>
Subject: [EXTERNAL] RE: [edk2-devel] [PATCH] RedfishPkg/RedfishPlatformCredentialLib: IPMI implementation


**CAUTION: The e-mail below is from an external source. Please exercise caution before opening attachments, clicking links, or following guidance.**

[AMD Official Use Only - General]



> -----Original Message-----
> From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Igor
> Kulchytskyy via groups.io
> Sent: Thursday, October 27, 2022 10:42 PM
> To: devel@edk2.groups.io; nicklew@...; Chang, Abner
> <Abner.Chang@...>
> Cc: Nick Ramirez <nramirez@...>
> Subject: Re: [edk2-devel] [PATCH] RedfishPkg/RedfishPlatformCredentialLib:
> IPMI implementation
>
> Caution: This message originated from an External Source. Use proper
> caution when opening attachments, clicking links, or responding.
>
>
> Hi Nickle,
> Pleased, see my comments on your questions below.
>
> Another point I missed in my previous mail.
> You have that function in the library to get credentials and it is
> used by RedfishCredentialsDxe driver to create the protocol which in
> its turn will be used by other Redfish modules.
> We do not know how many modules and how many times will call this
> function during boot. Right?
> And on each call of this function you call IPMI command. That command
> will create new Redfish account on BMC side according to Redfish HI specification:
>
> " If the Get Bootstrap Account Credentials command has been issued and
> responds with the completion code 00h, a bootstrap account shall be
> added to the manager's account collection and enabled. If the Get
> Bootstrap Account Credentials command is sent subsequent times and
> responds with the completion code 00h, a new account shall be created
> based on the newly generated credentials. Any existing bootstrap accounts shall remain active."
>
> As I know BMC may have some restrictions on the number of Redfish
> accounts they can support.
> And because of that BOS may hit this limit. Which is not good.
> On the other hand I'm not sure we need to have different credentials
> for different modules? All those modules are part of FW. And all of
> them will be associated with the same RoleID (FW role) on BMC side.
> So, all of them may use the same credentials.
> Could we cash the credentials on first call of that
Yes, this is something we have to avoid. Many accounts will be created while each of Redfish client module requests a credential. FW can save it in EFI variable and delete it at proper timing. Unfortunately the credential delivering via EFI variable section was deprecated, otherwise we can deliver the credential to OS through EFI variable with disabling the bootstrap credential at exit boot service.

Abner

> RedfishCredentialGetAuthInfo and then use those cashed credentials on
> subsequential calls?
> It will also may save a boot time, since there is no need to send IPMI
> command.
>
> Thank you,
> Igor
>
> -----Original Message-----
> From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Nickle
> Wang via groups.io
> Sent: Thursday, October 27, 2022 9:26 AM
> To: devel@edk2.groups.io; Igor Kulchytskyy <igork@...>;
> abner.chang@...
> Cc: Nick Ramirez <nramirez@...>
> Subject: [EXTERNAL] Re: [edk2-devel] [PATCH]
> RedfishPkg/RedfishPlatformCredentialLib: IPMI implementation
>
>
> **CAUTION: The e-mail below is from an external source. Please
> exercise caution before opening attachments, clicking links, or
> following guidance.**
>
> Hi Igor,
>
> Thank you for your help to review my changes.
>
> > And it will be blocked by our IPMI call.
>
> I see your point. So, BIOS should never be the person to shutdown
> credential service because BIOS always get executed prior to OS, right?
>
> Igor: Yes, my point is that we should not shutdown credential service
> from BIOS. Even if OS sends that IPMI command, new account will be
> created and BIOS credentials will not be compromised.
>
> > Should it be configured with some PCD? Maybe user may select in
> > Setup
> what method should be used? Or it could be build time configuration?
>
> I have below assumption while I implemented the library. I admit this
> is not always true.
>
> No Auth: I think this is rare case for Redfish service which gives
> anonymous privilege to change BIOS settings.
> Basic Auth: this is the authentication method which uses username and
> password to build base64 encoded string.
> Session Auth: I assume that client must have a session token first and
> then use this authentication method. Can we use username and password
> to generate session token on our own? If my memory serves me
> correctly, client has to do a login with username and password first
> and then client can receive session token from server.
>
> Igor: BIOS will use the credentials to create session. It should send
> POST request to the session URI with user name and password to create session.
> If a session created successfully then on response BMC returns header
> "X- Auth-Token" which then used for the subsequential calls.
>
> If we really like to know what authentication method that Redfish
> service used, we can issue a HTTP query to "/redfish/v1/Systems" with "No Auth".
> Then we can know what authentication method is required by reading the
> "WWW-Authenticate " filed in returned HTTP header.
>
> Igor: As my understanding, even if you include authentication header
> (Base64 encoded) in the request to BMC and BMC has NoAuth
> configuration, then that authentication header would be just ignored by BMC.
>
> Thanks,
> Nickle
>
> -----Original Message-----
> From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Igor
> Kulchytskyy via groups.io
> Sent: Wednesday, October 26, 2022 11:26 PM
> To: Nickle Wang <nicklew@...>; devel@edk2.groups.io;
> abner.chang@...
> Cc: Nick Ramirez <nramirez@...>
> Subject: Re: [edk2-devel] [PATCH] RedfishPkg/RedfishPlatformCredentialLib:
> IPMI implementation
>
> External email: Use caution opening links or attachments
>
>
> Hi Nickle,
> I would like to discuss that DisableBootstrapControl flag and how it
> is used in our implementation.
> According to Redfish HI specification we can use this flag to disable
> credential bootstrapping control.
> It can be disabled permanently or till next reboot of the host or
> service. That depend on the  EnableAfterReset  setting on BMC side:
> CredentialBootstrapping (v1.3+)
> { object The credential bootstrapping settings for this interface.
>         EnableAfterReset (v1.3+) Boolean read-write (null) An
> indication of whether credential bootstrapping is enabled after a reset for this interface.
>         Enabled (v1.3+) Boolean read-write (null) An indication of
> whether credential bootstrapping is enabled for this interface.
>         RoleId (v1.3+) string read-write The role used for the
> bootstrap account created for this interface.
> }
> So, if EnableAfterReset set to false, that means BMC will response
> with 0x80 error and will not return any credentials after reboot. And
> BIOS BMC communication will fail.
> Another concern with  disabling credential bootstrapping control is
> that we do it on Exit Boot event before passing a control to OS.
> But OS may also need to communicate to BMC through Redfish Host
> Interface to post some information. And it will be blocked by our IPMI call.
> We create that SMBIOS Type 42 table with Redfish Host Interface
> settings which can be used by OS to communicate with BMC. But without
> the credentials it will not be possible.
>
> Another question is AuthMethod parameter you initialize in this library:
> *AuthMethod = AuthMethodHttpBasic;
> According to Redfish HI specification 3 methods may be used - No Auth,
> Basic Auth and Session Auth.
> Basic Auth and Session Auth methods are required the credentials to be
> used by BIOS. And both of them should be supported by BMC.
> And your high level function RedfishCreateLibredfishService also
> supports of creation Basic or Session Auth service.
> I'm not sure why low level library which is created to get credentials
> from BMC should decide what Authentication method should be used?
> Should it be configured with some PCD? Maybe user may select in Setup
> what method should be used? Or it could be build time configuration?
>
> Thank you,
> Igor
>
> -----Original Message-----
> From: Nickle Wang <nicklew@...>
> Sent: Tuesday, October 25, 2022 4:24 AM
> To: devel@edk2.groups.io; abner.chang@...
> Cc: Nick Ramirez <nramirez@...>; Igor Kulchytskyy
> <igork@...>
> Subject: [EXTERNAL] RE: [edk2-devel] [PATCH]
> RedfishPkg/RedfishPlatformCredentialLib: IPMI implementation
>
>
> **CAUTION: The e-mail below is from an external source. Please
> exercise caution before opening attachments, clicking links, or
> following guidance.**
>
> Thanks for your review comments, Abner! I will update new version
> patch later. The CI build error will be handled together.
>
> > please add Igor as reviewer too
> Sure!
>
>
> > +  *UserId = AllocateZeroPool (sizeof (CHAR8) * USERNAME_MAX_SIZE);
> > + if
> [Chang, Abner]
> Allocation memory with the size (USERNAME_MAX_LENGTH + 1)  for both
> BootUsername and BootstrapPassword?   Because the maximum number of
> characters defined in the spec is USERNAME_MAX_LENGTH for the
> user/password.
>
> Yes, the additional one byte is for NULL terminator.
> USERNAME_MAX_LENGTH is defined as 16 and follow host interface
> specification.
>
> Regards,
> Nickle
>
> -----Original Message-----
> From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Chang,
> Abner via groups.io
> Sent: Saturday, October 22, 2022 3:01 PM
> To: Nickle Wang <nicklew@...>; devel@edk2.groups.io
> Cc: Nick Ramirez <nramirez@...>; Igor Kulchytskyy
> <igork@...>
> Subject: Re: [edk2-devel] [PATCH] RedfishPkg/RedfishPlatformCredentialLib:
> IPMI implementation
>
> External email: Use caution opening links or attachments
>
>
> [AMD Official Use Only - General]
>
> Hi Nickle, please add Igor as reviewer too. My comments is in below,
>
> > -----Original Message-----
> > From: Nickle Wang <nicklew@...>
> > Sent: Thursday, October 20, 2022 10:55 AM
> > To: devel@edk2.groups.io
> > Cc: Chang, Abner <Abner.Chang@...>; Nick Ramirez
> > <nramirez@...>
> > Subject: [PATCH] RedfishPkg/RedfishPlatformCredentialLib: IPMI
> > implementation
> >
> > Caution: This message originated from an External Source. Use proper
> > caution when opening attachments, clicking links, or responding.
> >
> >
> > This library follows Redfish Host Interface specification and use
> > IPMI command to get bootstrap account credential(NetFn 2Ch, Command
> > 02h)
> from BMC.
> > RedfishHostInterfaceDxe will use this credential for the following
> > communication between BIOS and BMC.
> >
> > Cc: Abner Chang <abner.chang@...>
> > Cc: Nick Ramirez <nramirez@...>
> > Signed-off-by: Nickle Wang <nicklew@...>
> > ---
> >  .../RedfishPlatformCredentialLib.c            | 273 ++++++++++++++++++
> >  .../RedfishPlatformCredentialLib.h            |  75 +++++
> >  .../RedfishPlatformCredentialLib.inf          |  37 +++
> [Chang, Abner]
> Could we name this library RedfishPlatformCredentialIpmi so the naming
> style is consistent with RedfishPlatformCredentialNull?
>
> >  3 files changed, 385 insertions(+)
> >  create mode 100644
> >
> RedfishPkg/Library/RedfishPlatformCredentialLib/RedfishPlatformCredent
> ial
> Lib.
> > c
> >  create mode 100644
> >
> RedfishPkg/Library/RedfishPlatformCredentialLib/RedfishPlatformCredent
> ial
> Lib.
> > h
> >  create mode 100644
> > RedfishPkg/Library/RedfishPlatformCredentialLib/RedfishPlatformCrede
> > nt
> > ialLib.i
> > nf
> >
> > diff --git
> > a/RedfishPkg/Library/RedfishPlatformCredentialLib/RedfishPlatformCre
> > de
> > ntialLi
> > b.c
> > b/RedfishPkg/Library/RedfishPlatformCredentialLib/RedfishPlatformCre
> > de
> > ntialLi
> > b.c
> > new file mode 100644
> > index 0000000000..23a15ab1fa
> > --- /dev/null
> > +++ b/RedfishPkg/Library/RedfishPlatformCredentialLib/RedfishPlatfor
> > +++ mC
> > +++ re
> > +++ dentialLib.c
> > @@ -0,0 +1,273 @@
> > +/** @file
> > +*
> > +*  Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights
> reserved.
> > +*
> > +*  SPDX-License-Identifier: BSD-2-Clause-Patent
> [Chang, Abner]
> We can have "@par Revision Reference:"  in the file header to point
> out the spec.
> https://nam11.safelinks.protection.outlook.com/?url=https%3A%2F%2Fnam12.safelinks.protection.outlook.com%2F%3Furl%3Dhttps%253A%252F%252Fnam1&amp;data=05%7C01%7Cnicklew%40nvidia.com%7C3f7c98d402b8471f95d408dab8fdeb00%7C43083d15727340c1b7db39efd9ccc17a%7C0%7C0%7C638025697967855556%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&amp;sdata=90NlFqDGaEtk5kMibeuQ3%2FzQNn3ANJn1LcF6RNqsJJ0%3D&amp;reserved=0
> 1.safelinks.protection.outlook.com%2F%3Furl%3Dhttps%253A%252F%252Fnam1
> &amp;data=05%7C01%7Cigork%40ami.com%7C224e78526d7d45a7b31108dab8f42ac1
> %7C27e97857e15f486cb58e86c2b3040f93%7C1%7C0%7C638025656093102767%7CUnk
> nown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWw
> iLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&amp;sdata=YN52FOx%2F%2F1YYG8Nl86vu7zlz
> M%2BpLMk3Ym0RNPLxLKqw%3D&amp;reserved=0
> 2.safelinks.protection.outlook.com%2F%3Furl%3Dhttps%253A%252F%252Fnam1
> &amp;data=05%7C01%7Cnicklew%40nvidia.com%7C90696ea8811e49e371a708dab8e
> be2d8%7C43083d15727340c1b7db39efd9ccc17a%7C0%7C0%7C638025620543993279%
> 7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik
> 1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&amp;sdata=CyvRgMZREOk5Yf0hU3CmH%2
> B08ktxMYw%2Bixr4UVywfrAQ%3D&amp;reserved=0
> 1.safelinks.protection.outlook.com%2F%3Furl%3Dhttps%253A%252F%252Fww&a
> mp;data=05%7C01%7Cigork%40ami.com%7C2b5b562c02c04c90d51208dab8b8c0fd%7
> C27e97857e15f486cb58e86c2b3040f93%7C1%7C0%7C638025400915295621%7CUnkno
> wn%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiL
> CJXVCI6Mn0%3D%7C3000%7C%7C%7C&amp;sdata=Uy%2B3HS336N3rgNSESPcyOPGX3eOR
> 48hekdz08nLtJU4%3D&amp;reserved=0
> w.dmtf.org%2Fsites%2Fdefault%2Ffiles%2Fstandards%2Fdocuments%2FDSP
> 0270_1.3.0.pdf&amp;data=05%7C01%7Cabner.chang%40amd.com%7C074aa
> e162fba49409af408dab8297c03%7C3dd8961fe4884e608e11a82d994e183d%7C
> 0%7C0%7C638024786060127888%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiM
> C4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000
> %7C%7C%7C&amp;sdata=yY6hhKjQfVqmNuufbeDNk%2B2FKrebHyIAyS9Ya4
> szE3Y%3D&amp;reserved=0
>
> > +*
> > +**/
> > +
> > +#include "RedfishPlatformCredentialLib.h"
> > +
> > +//
> > +// Global flag of controlling credential service // BOOLEAN
> > +mRedfishServiceStopped = FALSE;
> > +
> > +/**
> > +  Notify the Redfish service provide to stop provide configuration
> > +service to this
> > platform.
> > +
> > +  This function should be called when the platfrom is about to
> > + leave the safe
> > environment.
> > +  It will notify the Redfish service provider to abort all logined
> > + session, and prohibit  further login with original auth info.
> > + GetAuthInfo() will return EFI_UNSUPPORTED once this  function is
> returned.
> > +
> > +  @param[in]   This                Pointer to
> > EDKII_REDFISH_CREDENTIAL_PROTOCOL instance.
> > +  @param[in]   ServiceStopType     Reason of stopping Redfish service.
> > +
> > +  @retval EFI_SUCCESS              Service has been stoped successfully.
> > +  @retval EFI_INVALID_PARAMETER    This is NULL.
> > +  @retval Others                   Some error happened.
> > +
> > +**/
> > +EFI_STATUS
> > +EFIAPI
> > +LibStopRedfishService (
> > +  IN     EDKII_REDFISH_CREDENTIAL_PROTOCOL           *This,
> > +  IN     EDKII_REDFISH_CREDENTIAL_STOP_SERVICE_TYPE
> ServiceStopType
> > +  )
> > +{
> > +  EFI_STATUS  Status;
> > +
> > +  if ((ServiceStopType <= ServiceStopTypeNone) || (ServiceStopType
> > + >=
> > ServiceStopTypeMax)) {
> > +    return EFI_INVALID_PARAMETER;
> > +  }
> > +
> > +  //
> > +  // Raise flag first
> > +  //
> > +  mRedfishServiceStopped = TRUE;
> > +
> > +  //
> > +  // Notify BMC to disable credential bootstrapping support.
> > +  //
> > +  Status = GetBootstrapAccountCredentials (TRUE, NULL, NULL);  if
> > + (EFI_ERROR (Status)) {
> > +    DEBUG ((DEBUG_ERROR, "%a: fail to disable bootstrap credential:
> > + %r\n",
> > __FUNCTION__, Status));
> > +    return Status;
> > +  }
> > +
> > +  return EFI_SUCCESS;
> > +}
> > +
> > +/**
> > +  Notification of Exit Boot Service.
> > +
> > +  @param[in]  This    Pointer to EDKII_REDFISH_CREDENTIAL_PROTOCOL.
> > +**/
> > +VOID
> > +EFIAPI
> > +LibCredentialExitBootServicesNotify (
> > +  IN  EDKII_REDFISH_CREDENTIAL_PROTOCOL  *This
> > +  )
> > +{
> > +  //
> > +  // Stop the credential support when system is about to enter OS.
> > +  //
> > +  LibStopRedfishService (This, ServiceStopTypeExitBootService); }
> > +
> > +/**
> > +  Notification of End of DXe.
> > +
> > +  @param[in]  This    Pointer to EDKII_REDFISH_CREDENTIAL_PROTOCOL.
> > +**/
> > +VOID
> > +EFIAPI
> > +LibCredentialEndOfDxeNotify (
> > +  IN  EDKII_REDFISH_CREDENTIAL_PROTOCOL  *This
> > +  )
> > +{
> > +  //
> > +  // Do nothing now.
> > +  // We can stop credential support when system reach end-of-dxe
> > +for security
> > reason.
> > +  //
> > +}
> > +
> > +/**
> > +  Function to retrieve temporary use credentials for the UEFI
> > +redfish client
> [Chang, Abner]
> We miss the functionality to disable bootstrap credential service in
> the function description.
>
> > +
> > +  @param[in]  DisableBootstrapControl
> > +                                      TRUE - Tell the BMC to disable the bootstrap credential
> > +                                             service to ensure no one else gains credentials
> > +                                      FALSE  Allow the bootstrap
> > + credential service to continue  @param[out] BootstrapUsername
> > +                                      A pointer to a UTF-8 encoded
> > + string for the credential
> > username
> > +                                      When DisableBootstrapControl
> > + is TRUE, this pointer can be NULL
> > +
> > +  @param[out] BootstrapPassword
> > +                                      A pointer to a UTF-8 encoded
> > + string for the credential
> > password
> > +                                      When DisableBootstrapControl
> > + is TRUE, this pointer can be NULL
> > +
> > +  @retval  EFI_SUCCESS                Credentials were successfully fetched and
> > returned
> > +  @retval  EFI_INVALID_PARAMETER      BootstrapUsername or
> > BootstrapPassword is NULL when DisableBootstrapControl
> > +                                      is set to FALSE
> > +  @retval  EFI_DEVICE_ERROR           An IPMI failure occurred
> [Chang, Abner]
> The return status should also include the status of disabling
> bootstrap credential.
>
>
> > +**/
> > +EFI_STATUS
> > +GetBootstrapAccountCredentials (
> > +  IN BOOLEAN DisableBootstrapControl,
> > +  IN OUT CHAR8 *BootstrapUsername, OPTIONAL
> > +  IN OUT CHAR8  *BootstrapPassword    OPTIONAL
> > +  )
> > +{
> > +  EFI_STATUS                                  Status;
> > +  IPMI_BOOTSTRAP_CREDENTIALS_COMMAND_DATA     CommandData;
> > +  IPMI_BOOTSTRAP_CREDENTIALS_RESULT_RESPONSE  ResponseData;
> > +  UINT32                                      ResponseSize;
> > +
> > +  if (!PcdGetBool (PcdIpmiFeatureEnable)) {
> > +    DEBUG ((DEBUG_ERROR, "%a: IPMI is not enabled! Unable to fetch
> > + Redfish
> > credentials\n", __FUNCTION__));
> > +    return EFI_UNSUPPORTED;
> > +  }
> > +
> > +  //
> > +  // NULL buffer check
> > +  //
> > +  if (!DisableBootstrapControl && ((BootstrapUsername == NULL) ||
> > (BootstrapPassword == NULL))) {
> > +    return EFI_INVALID_PARAMETER;
> > +  }
> > +
> > +  DEBUG ((DEBUG_VERBOSE, "%a: Disable bootstrap control: 0x%x\n",
> > + __FUNCTION__, DisableBootstrapControl));
> > +
> > +  //
> > +  // IPMI callout to NetFn 2C, command 02
> > +  //    Request data:
> > +  //      Byte 1: REDFISH_IPMI_GROUP_EXTENSION
> > +  //      Byte 2: DisableBootstrapControl
> > +  //
> > +  CommandData.GroupExtensionId        =
> REDFISH_IPMI_GROUP_EXTENSION;
> > +  CommandData.DisableBootstrapControl = (DisableBootstrapControl ?
> > + REDFISH_IPMI_BOOTSTRAP_CREDENTIAL_DISABLE :
> > + REDFISH_IPMI_BOOTSTRAP_CREDENTIAL_ENABLE);
> > +
> > +  ResponseSize = sizeof (ResponseData);
> > +
> > +  //
> > +  //    Response data:
> > +  //      Byte 1    : Completion code
> > +  //      Byte 2    : REDFISH_IPMI_GROUP_EXTENSION
> > +  //      Byte 3-18 : Username
> > +  //      Byte 19-34: Password
> > +  //
> > +  Status = IpmiSubmitCommand (
> > +             IPMI_NETFN_GROUP_EXT,
> > +             REDFISH_IPMI_GET_BOOTSTRAP_CREDENTIALS_CMD,
> > +             (UINT8 *)&CommandData,
> > +             sizeof (CommandData),
> > +             (UINT8 *)&ResponseData,
> > +             &ResponseSize
> > +             );
> > +
> > +  if (EFI_ERROR (Status)) {
> > +    DEBUG ((DEBUG_ERROR, "%a: IPMI transaction failure.
> > + Returning\n",
> > __FUNCTION__));
> > +    ASSERT_EFI_ERROR (Status);
> > +    return Status;
> > +  } else {
> > +    if (ResponseData.CompletionCode != IPMI_COMP_CODE_NORMAL) {
> > +      if (ResponseData.CompletionCode ==
> > REDFISH_IPMI_COMP_CODE_BOOTSTRAP_CREDENTIAL_DISABLED) {
> > +        DEBUG ((DEBUG_ERROR, "%a: bootstrap credential support was
> > disabled\n", __FUNCTION__));
> > +        return EFI_ACCESS_DENIED;
> > +      }
> > +
> > +      DEBUG ((DEBUG_ERROR, "%a: Completion code = 0x%x.
> > + Returning\n",
> > __FUNCTION__, ResponseData.CompletionCode));
> > +      return EFI_PROTOCOL_ERROR;
> > +    } else if (ResponseData.GroupExtensionId !=
> > REDFISH_IPMI_GROUP_EXTENSION) {
> > +      DEBUG ((DEBUG_ERROR, "%a: Group Extension Response = 0x%x.
> > Returning\n", __FUNCTION__, ResponseData.GroupExtensionId));
> > +      return EFI_DEVICE_ERROR;
> > +    } else {
> > +      if (BootstrapUsername != NULL) {
> > +        CopyMem (BootstrapUsername, ResponseData.Username,
> > USERNAME_MAX_LENGTH);
> > +        //
> > +        // Manually append null-terminator in case 16 characters
> > + username
> > returned.
> > +        //
> > +        BootstrapUsername[USERNAME_MAX_LENGTH] = '\0';
> > +      }
> > +
> > +      if (BootstrapPassword != NULL) {
> > +        CopyMem (BootstrapPassword, ResponseData.Password,
> > PASSWORD_MAX_LENGTH);
> > +        //
> > +        // Manually append null-terminator in case 16 characters
> > + password
> > returned.
> > +        //
> > +        BootstrapPassword[PASSWORD_MAX_LENGTH] = '\0';
> > +      }
> > +    }
> > +  }
> > +
> > +  return Status;
> > +}
> > +
> > +/**
> > +  Retrieve platform's Redfish authentication information.
> > +
> > +  This functions returns the Redfish authentication method together
> > + with the user Id and  password.
> > +  - For AuthMethodNone, the UserId and Password could be used for
> > + HTTP
> > header authentication
> > +    as defined by RFC7235.
> > +  - For AuthMethodRedfishSession, the UserId and Password could be
> > + used for
> > Redfish
> > +    session login as defined by  Redfish API specification (DSP0266).
> > +
> > +  Callers are responsible for and freeing the returned string storage.
> > +
> > +  @param[in]   This                Pointer to
> > EDKII_REDFISH_CREDENTIAL_PROTOCOL instance.
> > +  @param[out]  AuthMethod          Type of Redfish authentication method.
> > +  @param[out]  UserId              The pointer to store the returned UserId
> string.
> > +  @param[out]  Password            The pointer to store the returned
> Password
> > string.
> > +
> > +  @retval EFI_SUCCESS              Get the authentication information
> successfully.
> > +  @retval EFI_ACCESS_DENIED        SecureBoot is disabled after EndOfDxe.
> > +  @retval EFI_INVALID_PARAMETER    This or AuthMethod or UserId or
> > Password is NULL.
> > +  @retval EFI_OUT_OF_RESOURCES     There are not enough memory
> resources.
> > +  @retval EFI_UNSUPPORTED          Unsupported authentication method is
> > found.
> > +
> > +**/
> > +EFI_STATUS
> > +EFIAPI
> > +LibCredentialGetAuthInfo (
> > +  IN  EDKII_REDFISH_CREDENTIAL_PROTOCOL  *This,
> > +  OUT EDKII_REDFISH_AUTH_METHOD          *AuthMethod,
> > +  OUT CHAR8                              **UserId,
> > +  OUT CHAR8                              **Password
> > +  )
> > +{
> > +  EFI_STATUS  Status;
> > +
> > +  if ((AuthMethod == NULL) || (UserId == NULL) || (Password == NULL)) {
> > +    return EFI_INVALID_PARAMETER;
> > +  }
> > +
> > +  *UserId   = NULL;
> > +  *Password = NULL;
> > +
> > +  if (mRedfishServiceStopped) {
> > +    DEBUG ((DEBUG_ERROR, "%a: credential service is stopped due to
> > + security
> > reason\n", __FUNCTION__));
> > +    return EFI_ACCESS_DENIED;
> > +  }
> > +
> > +  *AuthMethod = AuthMethodHttpBasic;
> > +
> > +  *UserId = AllocateZeroPool (sizeof (CHAR8) * USERNAME_MAX_SIZE);
> > + if
> [Chang, Abner]
> Allocation memory with the size (USERNAME_MAX_LENGTH + 1)  for both
> BootUsername and BootstrapPassword?   Because the maximum number of
> characters defined in the spec is USERNAME_MAX_LENGTH for the
> user/password.
>
>
> > + (*UserId == NULL) {
> > +    return EFI_OUT_OF_RESOURCES;
> > +  }
> > +
> > +  *Password = AllocateZeroPool (sizeof (CHAR8) *
> > + PASSWORD_MAX_SIZE); if (*Password == NULL) {
> > +    return EFI_OUT_OF_RESOURCES;
> > +  }
> > +
> > +  Status = GetBootstrapAccountCredentials (FALSE, *UserId,
> > + *Password); if (EFI_ERROR (Status)) {
> > +    DEBUG ((DEBUG_ERROR, "%a: fail to get bootstrap credential:
> > + %r\n",
> > __FUNCTION__, Status));
> > +    return Status;
> > +  }
> > +
> > +  return EFI_SUCCESS;
> > +}
> > diff --git
> > a/RedfishPkg/Library/RedfishPlatformCredentialLib/RedfishPlatformCre
> > de
> > ntialLi
> > b.h
> > b/RedfishPkg/Library/RedfishPlatformCredentialLib/RedfishPlatformCre
> > de
> > ntialLi
> > b.h
> > new file mode 100644
> > index 0000000000..5b448e01be
> > --- /dev/null
> > +++ b/RedfishPkg/Library/RedfishPlatformCredentialLib/RedfishPlatfor
> > +++ mC
> > +++ re
> > +++ dentialLib.h
> > @@ -0,0 +1,75 @@
> > +/** @file
> > +*
> > +*  Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights
> reserved.
> > +*
> > +*  SPDX-License-Identifier: BSD-2-Clause-Patent
> > +*
> > +**/
> > +#include <Uefi.h>
> > +#include <IndustryStandard/Ipmi.h>
> > +#include <Protocol/EdkIIRedfishCredential.h>
> > +#include <Library/BaseLib.h>
> > +#include <Library/BaseMemoryLib.h>
> > +#include <Library/DebugLib.h>
> > +#include <Library/IpmiBaseLib.h>
> > +#include <Library/MemoryAllocationLib.h> #include
> > +<Library/RedfishCredentialLib.h>
> > +
> > +#define REDFISH_IPMI_GROUP_EXTENSION                          0x52
> > +#define REDFISH_IPMI_GET_BOOTSTRAP_CREDENTIALS_CMD            0x02
> > +#define REDFISH_IPMI_BOOTSTRAP_CREDENTIAL_ENABLE              0xA5
> > +#define REDFISH_IPMI_BOOTSTRAP_CREDENTIAL_DISABLE             0x00
> > +#define
> REDFISH_IPMI_COMP_CODE_BOOTSTRAP_CREDENTIAL_DISABLED
> > 0x80
> > +
> > +//
> > +// Per Redfish Host Interface Specification 1.3, The maximum lenght
> > +of // username and password is 16 characters long.
> > +//
> > +#define USERNAME_MAX_LENGTH  16
> > +#define PASSWORD_MAX_LENGTH  16
> > +#define USERNAME_MAX_SIZE    (USERNAME_MAX_LENGTH + 1)  //
> NULL
> > terminator
> > +#define PASSWORD_MAX_SIZE    (PASSWORD_MAX_LENGTH + 1)  //
> NULL
> > terminator
> > +
> > +#pragma pack(1)
> > +///
> > +/// The definition of IPMI command to get bootstrap account
> > +credentials /// typedef struct {
> > +  UINT8    GroupExtensionId;
> > +  UINT8    DisableBootstrapControl;
> > +} IPMI_BOOTSTRAP_CREDENTIALS_COMMAND_DATA;
> > +
> > +///
> > +/// The response data of getting bootstrap credential /// typedef
> > +struct {
> > +  UINT8    CompletionCode;
> > +  UINT8    GroupExtensionId;
> > +  CHAR8    Username[USERNAME_MAX_LENGTH];
> > +  CHAR8    Password[PASSWORD_MAX_LENGTH];
> > +} IPMI_BOOTSTRAP_CREDENTIALS_RESULT_RESPONSE;
> > +
> > +#pragma pack()
> > +
> > +/**
> > +  Function to retrieve temporary use credentials for the UEFI
> > +redfish client
> [Chang, Abner]
> We miss the functionality to disable bootstrap credential service in
> the function description.
>
> > +
> > +  @param[in]  DisableBootstrapControl
> > +                                      TRUE - Tell the BMC to disable the bootstrap credential
> > +                                             service to ensure no one else gains credentials
> > +                                      FALSE  Allow the bootstrap
> > + credential service to continue  @param[out] BootstrapUsername
> > +                                      A pointer to a UTF-8 encoded
> > + string for the credential username
> > +
> > +  @param[out] BootstrapPassword
> > +                                      A pointer to a UTF-8 encoded
> > + string for the credential password
> > +
> > +  @retval  EFI_SUCCESS                Credentials were successfully fetched and
> > returned
> [Chang, Abner]
> Or the bootstrap credential service is disabled successfully, right?
>
> > +  @retval  EFI_DEVICE_ERROR           An IPMI failure occurred
> > +**/
> > +EFI_STATUS
> > +GetBootstrapAccountCredentials (
> > +  IN BOOLEAN    DisableBootstrapControl,
> > +  IN OUT CHAR8  *BootstrapUsername,
> > +  IN OUT CHAR8  *BootstrapPassword
> > +  );
> > diff --git
> > a/RedfishPkg/Library/RedfishPlatformCredentialLib/RedfishPlatformCre
> > de
> > ntialLi
> > b.inf
> > b/RedfishPkg/Library/RedfishPlatformCredentialLib/RedfishPlatformCre
> > de
> > ntialLi
> > b.inf
> > new file mode 100644
> > index 0000000000..a990d28363
> > --- /dev/null
> > +++ b/RedfishPkg/Library/RedfishPlatformCredentialLib/RedfishPlatfor
> > +++ mC
> > +++ re
> > +++ dentialLib.inf
> > @@ -0,0 +1,37 @@
> > +## @file
> > +#
> > +# Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights
> reserved.
> > +#
> > +#  SPDX-License-Identifier: BSD-2-Clause-Patent # ##
> > +
> > +[Defines]
> > +  INF_VERSION                    = 0x0001000b
> > +  BASE_NAME                      = RedfishPlatformCredentialLib
> > +  FILE_GUID                      = 9C45D622-4C66-417F-814C-F76246D97233
> > +  MODULE_TYPE                    = DXE_DRIVER
> > +  VERSION_STRING                 = 1.0
> > +  LIBRARY_CLASS                  = RedfishPlatformCredentialLib
> > +
> > +[Sources]
> > +  RedfishPlatformCredentialLib.c
> > +
> > +[Packages]
> > +  MdePkg/MdePkg.dec
> > +  MdeModulePkg/MdeModulePkg.dec
> > +  RedfishPkg/RedfishPkg.dec
> > +  IpmiFeaturePkg/IpmiFeaturePkg.dec
> [Chang, Abner]
> Could you please add a comment to the reference  of IpmiFeaturePkg? We
> have to give customers a notice that the dependence of "edk2-
> platforms/Features/Intel/OutOfBandManagement/". They have to add the
> path to PACKAGES_PATH. You also have to skip this dependence in the
> RedfishPkg.yaml to avoid the CI error.
>
> Another thing is I propose to move out IpmiFeaturePkg from edk2-
> platforms/Features/Intel/OutOfBandManagement to edk2-
> platforms/Features/ManageabilityPkg  that also provides the
> implementation of PLDM/MCTP/IPMI/KCS.  I had an initial talk with
> IpmiFeaturePkg owner and get the positive response on this proposal. I
> will kick off the discussion on the dev mailing list. That is to say
> this module may need a little bit change later, however that is good
> to me having this implementation now.
> Thanks
> Abner
> > +
> > +[LibraryClasses]
> > +  UefiLib
> > +  DebugLib
> > +  IpmiBaseLib
> > +  MemoryAllocationLib
> > +  BaseMemoryLib
> > +
> > +[Pcd]
> > +  gIpmiFeaturePkgTokenSpaceGuid.PcdIpmiFeatureEnable
> > +
> > +[Depex]
> > +  TRUE
> > --
> > 2.17.1
>
>
>
>
>
> -The information contained in this message may be confidential and
> proprietary to American Megatrends (AMI). This communication is
> intended to be read only by the individual or entity to whom it is
> addressed or by their designee. If the reader of this message is not
> the intended recipient, you are on notice that any distribution of
> this message, in any form, is strictly prohibited. Please promptly
> notify the sender by reply e-mail or by telephone at 770-246-8600, and
> then delete or destroy all copies of the transmission.
>
>
>
>
>
>
>
>
>
>
> -The information contained in this message may be confidential and
> proprietary to American Megatrends (AMI). This communication is
> intended to be read only by the individual or entity to whom it is
> addressed or by their designee. If the reader of this message is not
> the intended recipient, you are on notice that any distribution of
> this message, in any form, is strictly prohibited. Please promptly
> notify the sender by reply e-mail or by telephone at 770-246-8600, and
> then delete or destroy all copies of the transmission.
>
>
>
>
-The information contained in this message may be confidential and proprietary to American Megatrends (AMI). This communication is intended to be read only by the individual or entity to whom it is addressed or by their designee. If the reader of this message is not the intended recipient, you are on notice that any distribution of this message, in any form, is strictly prohibited. Please promptly notify the sender by reply e-mail or by telephone at 770-246-8600, and then delete or destroy all copies of the transmission.
-The information contained in this message may be confidential and proprietary to American Megatrends (AMI). This communication is intended to be read only by the individual or entity to whom it is addressed or by their designee. If the reader of this message is not the intended recipient, you are on notice that any distribution of this message, in any form, is strictly prohibited. Please promptly notify the sender by reply e-mail or by telephone at 770-246-8600, and then delete or destroy all copies of the transmission.


Re: [PATCH V1 0/2] CryptoPkg bug fixes

Judah Vang
 

Hi Mike,

This is not my realm of expertise. I'm just trying to fix an issue that I ran into when enabling crypto.
Can I suggest that someone like the maintainers or someone who knows how the build works update the build?

Judah

-----Original Message-----
From: Kinney, Michael D <michael.d.kinney@...>
Sent: Wednesday, October 26, 2022 2:17 PM
To: Vang, Judah <judah.vang@...>; devel@edk2.groups.io; Sean Brogan <sean.brogan@...>
Cc: Wang, Jian J <jian.j.wang@...>; Mistry, Nishant C <nishant.c.mistry@...>
Subject: RE: [edk2-devel] [PATCH V1 0/2] CryptoPkg bug fixes

Hi Judah,

Does CryptoPkg.dsc break if DISABLE_SHA1_DEPRECATED_INTERFACE is defined in that DSC file [BuildOptions] section?

All packages in edk2 repo have a .ci.yaml file that provides the set of CI checks that are performed when a PR contains source changes to that package. Here is link to CryptoPkg.ci.yaml file:

https://github.com/tianocore/edk2/blob/master/CryptoPkg/CryptoPkg.ci.yaml

The section of this file that identifies the package build step is "CompilerPlugin".
It specifies the relative path to the DSC file to build to perform a package scoped build verification.

"CompilerPlugin": {
"DscPath": "CryptoPkg.dsc"
},

The easiest way to make sure there is build coverage for SHA1 disabled is to make sure this DSC file is updated to include builds with and without SHA1 disabled. SHA1 is enabled by default, so DSC file needs to be amended to perform additional build(s) of components that disable SHA1. This is a challenge because this define is used in both libraries and modules so the define needs to be global to cover library instances.


The define DISABLE_SHA1_DEPRECATED_INTERFACES is also used in the SecurityPkg, so that package may also need updates to get CI coverage with and without this define.

https://github.com/tianocore/edk2/search?q=DISABLE_SHA1_DEPRECATED_INTERFACES&type=code

I just did a search for similar defines in edk2 repo:
* ENABLE_MD5_DEPRECATED_INTERFACES
* DISABLE_SHA1_DEPRECATED_INTERFACES
* DISABLE_NEW_DEPRECATED_INTERFACES

Perhaps Sean can provide advice on how to get full CI coverage for these types of defines.

Best regards,

Mike


-----Original Message-----
From: Vang, Judah <judah.vang@...>
Sent: Wednesday, October 26, 2022 11:42 AM
To: Kinney, Michael D <michael.d.kinney@...>;
devel@edk2.groups.io
Cc: Wang, Jian J <jian.j.wang@...>; Mistry, Nishant C
<nishant.c.mistry@...>
Subject: RE: [edk2-devel] [PATCH V1 0/2] CryptoPkg bug fixes

Mike,

Can you explain #3? I have no idea how to update/modify the EDK2 CI.
I know for MTL, we have this define there by default, that is why when
I enabled crypto for RPMC feature for MTL we ran into the issue.

#4, I prefer a build error.

Judah

-----Original Message-----
From: Kinney, Michael D <michael.d.kinney@...>
Sent: Monday, October 24, 2022 10:22 AM
To: devel@edk2.groups.io; Vang, Judah <judah.vang@...>; Kinney,
Michael D <michael.d.kinney@...>
Subject: RE: [edk2-devel] [PATCH V1 0/2] CryptoPkg bug fixes

Hi Judah,

There was an update to CryptoPkg pushed yesterday.

1) There is a CryptoPkg/Readme.md with tables and DSC content for services that are
enabled in each phase. I think that needs updates too for the AES and KDF features.
2) The CryptoPkg.dsc file has recommended settings for PEI, DXE, SMM. I think
they need to be updated for the AES and KDF features.
3) It looks like the SHA1 disable caused a build break. I would like to see the
standard package builds for EDK II CI be updated to cover the failure case so
we know that this case is covered in the future. It looks like the default is
for SHA1 enabled and the build break is when define for SHA1 disabled is
asserted.
4) There is an overlap between the defines to deprecate MD5 and SH1 and the
structured PCD that allows those services to be disabled in the Crypto
Protocol/PPI. The defines to deprecate MD5 and SH1 extend into the BaseCryptLib
instance implementations such that a call to those services when static linking
will generate a build error instead of a runtime ASSERT(). Which behavior do
you prefer?

Best regards,

Mike

-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Judah
Vang
Sent: Monday, October 24, 2022 9:42 AM
To: devel@edk2.groups.io
Subject: [edk2-devel] [PATCH V1 0/2] CryptoPkg bug fixes

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

There is a #define to deprecate Sha1 functions but not all the Sha1
function are wrapped around this #define causing a build error. The
fix is to wrap all Sha1 functions with the #define.

Need crypto AES to be supported for PEI phase and need crypto KDF to
be supported for SMM phase.

Judah Vang (2):
CryptoPkg: Sha1 functions causing build errors
CryptoPkg: Need to enable crypto functions

CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf | 2 +-
CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf | 2 +-
CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.c | 14
+++++++++++++-
3 files changed, 15 insertions(+), 3 deletions(-)

--
2.35.1.windows.2





Re: [PATCH v4] NetworkPkg/WifiProfileSync: Add WiFi profile sync protocol support

Clark-williams, Zachary
 

++More for reviewal!

-----Original Message-----
From: Clark-williams, Zachary
Sent: Friday, October 28, 2022 1:10 PM
To: Kinney, Michael D <michael.d.kinney@...>; Rabeda, Maciej <maciej.rabeda@...>; Luo, Heng <heng.luo@...>; Kuo, Scottie <scottie.kuo@...>; Kuo, Ted <ted.kuo@...>; Dutkiewicz, Michal <michal.dutkiewicz@...>; devel@edk2.groups.io
Subject: RE: [PATCH v4] NetworkPkg/WifiProfileSync: Add WiFi profile sync protocol support

Thanks for the forward Mike!

Maciej and All,

If you could please review the PR below. I would like to get this review completed within the week.

Thanks,
Zack

-----Original Message-----
From: Kinney, Michael D <michael.d.kinney@...>
Sent: Thursday, October 27, 2022 1:09 PM
To: Rabeda, Maciej <maciej.rabeda@...>; Kinney, Michael D <michael.d.kinney@...>; Clark-williams, Zachary <zachary.clark-williams@...>
Subject: FW: [PATCH v4] NetworkPkg/WifiProfileSync: Add WiFi profile sync protocol support

Hi Maciej,

Can you please help review these NetworkPkg changes.

I am not sure if you monitor your linux.intel.com account as closely as your intel.com account.

Thanks,

Mike

-----Original Message-----
From: Clark-williams, Zachary <zachary.clark-williams@...>
Sent: Thursday, October 27, 2022 12:33 PM
To: Kinney, Michael D <michael.d.kinney@...>
Subject: FW: [PATCH v4] NetworkPkg/WifiProfileSync: Add WiFi profile sync protocol support

Hey Mike,

I'm struggling to get any feedback on this PR. Do you have any suggestions to get better visibility and responses so I can get this miving?

Thanks,
Zack

-----Original Message-----
From: Clark-williams, Zachary <zachary.clark-williams@...>
Sent: Thursday, October 27, 2022 12:31 PM
To: devel@edk2.groups.io
Cc: Zachary Clark-Williams <zclarkw112@...>; Maciej Rabeda <maciej.rabeda@...>; Fu Siyuan <siyuan.fu@...>; Wu, Jiaxin <jiaxin.wu@...>; Otcheretianski, Andrei <andrei.otcheretianski@...>; Clark-williams, Zachary <zachary.clark-williams@...>
Subject: [PATCH v4] NetworkPkg/WifiProfileSync: Add WiFi profile sync protocol support

From: Zachary Clark-Williams <zclarkw112@...>

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

Enables KVM and One Click Recovery WLAN capability with WiFi Profile Sync feature and protocol. Adding WiFiProfileSyncProtocol, which supports the profilesync driver operations for transferring WiFi profiles from AMT to the Supplicant. WiFiConnectionManager will check for the WifiProfileSyncProtocol and if found will operate on the premise of a One Click Recovery, or KVM flow with a Wifi profile provided by AMT.

Cc: Maciej Rabeda <maciej.rabeda@...>
Cc: Fu Siyuan <siyuan.fu@...>
Cc: Wu Jiaxin <jiaxin.wu@...>
Cc: Andrei Otcheretianski <andrei.otcheretianski@...>

Signed-off-by: Zachary Clark-Williams <zachary.clark-williams@...>
---
.../Protocol/WiFiProfileSyncProtocol.h | 83 ++++++++
NetworkPkg/NetworkPkg.dec | 3 +
.../WifiConnectionManagerDxe.inf | 3 +-
.../WifiConnectionMgrConfigNVDataStruct.h | 2 +-
.../WifiConnectionMgrDriver.c | 126 ++++++++----
.../WifiConnectionMgrDxe.h | 4 +-
.../WifiConnectionMgrImpl.c | 193 ++++++++++++++++--
.../WifiConnectionMgrMisc.c | 13 ++
8 files changed, 367 insertions(+), 60 deletions(-) create mode 100644 NetworkPkg/Include/Protocol/WiFiProfileSyncProtocol.h

diff --git a/NetworkPkg/Include/Protocol/WiFiProfileSyncProtocol.h b/NetworkPkg/Include/Protocol/WiFiProfileSyncProtocol.h
new file mode 100644
index 0000000000..e36daceabf
--- /dev/null
+++ b/NetworkPkg/Include/Protocol/WiFiProfileSyncProtocol.h
@@ -0,0 +1,83 @@
+/** @file
+ WiFi profile sync protocol. Supports One Click Recovery or KVM OS
+recovery
+ boot flow over WiFi.
+
+ Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent **/
+
+#ifndef WIFI_PROFILE_SYNC_PROTOCOL_H_
+#define WIFI_PROFILE_SYNC_PROTOCOL_H_
+
+#include <WifiConnectionManagerDxe/WifiConnectionMgrConfig.h>
+
+//
+// WiFi Profile Sync Protocol GUID variable.
+//
+extern EFI_GUID gEfiWiFiProfileSyncProtocolGuid;
+
+/**
+ Used by the WiFi connection manager to get the WiFi profile that AMT
+shared
+ and was stored in WiFi profile protocol. Aligns the AMT WiFi profile
+data to
+ the WiFi connection manager profile structure fo connection use.
+
+ @param[in, out] WcmProfile WiFi Connection Manager profile structure
+ @param[in, out] MacAddress MAC address from AMT saved to NiC MAC address
+
+ @retval EFI_SUCCESS Stored WiFi profile converted and returned succefully
+ @retval EFI_UNSUPPORTED Profile protocol sharing not supported or enabled
+ @retval EFI_NOT_FOUND No profiles to returned
+ @retval Others Error Occurred
+**/
+typedef
+EFI_STATUS
+(EFIAPI *WIFI_PROFILE_GET)(
+ IN OUT WIFI_MGR_NETWORK_PROFILE *Profile,
+ IN OUT EFI_80211_MAC_ADDRESS MacAddress
+ );
+
+/**
+ Saves the WiFi connection status recieved by the
+WiFiConnectionManager when
+ in a KVM OR One Click Recovery WLAN recovery flow. Input as
+ EFI_80211_CONNECT_NETWORK_RESULT_CODE then converted and stored as EFI_STATUS type.
+
+ @param[in] ConnectionStatus WiFi connection attempt results
+**/
+typedef
+VOID
+(EFIAPI *WIFI_SET_CONNECT_STATE)(
+ IN EFI_80211_CONNECT_NETWORK_RESULT_CODE ConnectionStatus
+ );
+
+/**
+ Retrieves the stored WiFi connection status when in either KVM OR One
+Click
+ Recovery WLAN recovery flow.
+
+ @retval EFI_SUCCESS WiFi connection completed succesfully
+ @retval Others Connection failure occurred
+**/
+typedef
+EFI_STATUS
+(EFIAPI *WIFI_GET_CONNECT_STATE)(
+ VOID
+ );
+
+//
+// WiFi Profile Sync Protocol structure.
+//
+typedef struct {
+ UINT32 Revision;
+ WIFI_SET_CONNECT_STATE WifiProfileSyncSetConnectState;
+ WIFI_GET_CONNECT_STATE WifiProfileSyncGetConnectState;
+ WIFI_PROFILE_GET WifiProfileSyncGetProfile;
+} EFI_WIFI_PROFILE_SYNC_PROTOCOL;
+
+/**
+ WiFi Profile Protocol revision number.
+
+ Revision 1: Initial version
+**/
+#define EFI_WIFI_PROFILE_SYNC_PROTOCOL_REVISION 1
+
+#endif // WIFI_PROFILE_SYNC_PROTOCOL_H_
diff --git a/NetworkPkg/NetworkPkg.dec b/NetworkPkg/NetworkPkg.dec index 5e43ebf8c5..53fb34c4a0 100644
--- a/NetworkPkg/NetworkPkg.dec
+++ b/NetworkPkg/NetworkPkg.dec
@@ -91,6 +91,9 @@
## Include/Protocol/HttpCallback.h
gEdkiiHttpCallbackProtocolGuid = {0x611114f1, 0xa37b, 0x4468, {0xa4, 0x36, 0x5b, 0xdd, 0xa1, 0x6a, 0xa2, 0x40}}

+ ## Include/Protocol/WiFiProfileSyncProtocol.h
+ gEfiWiFiProfileSyncProtocolGuid = {0x399a2b8a, 0xc267, 0x44aa, {0x9a,
+ 0xb4, 0x30, 0x58, 0x8c, 0xd2, 0x2d, 0xcc}}
+
[PcdsFixedAtBuild]
## The max attempt number will be created by iSCSI driver.
# @Prompt Max attempt number.
diff --git a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionManagerDxe.inf b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionManagerDxe.inf
index 4394b6f4bb..7e36016cf8 100644
--- a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionManagerDxe.inf
+++ b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionManagerDxe.inf
@@ -9,7 +9,7 @@
# 2). WPA2 Personal Network
# 3). EAP Networks (EAP-TLS, EAP-TTLS/MSCHAPv2 and PEAPv0/MSCHAPv2) # -# Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2019 - 2022, Intel Corporation. All rights
+reserved.<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -71,6 +71,7 @@
gEfiAdapterInformationProtocolGuid ## SOMETIMES_CONSUMES
gEfiSupplicantProtocolGuid ## SOMETIMES_CONSUMES
gEfiEapConfigurationProtocolGuid ## SOMETIMES_CONSUMES
+ gEfiWiFiProfileSyncProtocolGuid ## SOMETIMES_CONSUMES

[Guids]
gWifiConfigGuid ## PRODUCES ## GUID
diff --git a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrConfigNVDataStruct.h b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrConfigNVDataStruct.h
index b5518a74d8..dcc4bf7e27 100644
--- a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrConfigNVDataStruct.h
+++ b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrConfigNVDataS
+++ truct.h
@@ -25,7 +25,7 @@

#define PASSWORD_MIN_LEN 8
#define PASSWORD_MAX_LEN 63
-#define PASSWORD_STORAGE_SIZE 64
+#define PASSWORD_STORAGE_SIZE 65

#define EAP_IDENTITY_LEN 63
#define EAP_IDENTITY_SIZE 64
diff --git a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDriver.c b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDriver.c
index 67a01ca058..97ca7a9f0b 100644
--- a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDriver.c
+++ b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDriver.c
@@ -1,7 +1,7 @@
/** @file
The driver binding protocol for the WiFi Connection Manager.

- Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2019 - 2022, Intel Corporation. All rights
+ reserved.<BR>

SPDX-License-Identifier: BSD-2-Clause-Patent

@@ -39,6 +39,11 @@ EFI_GUID mWifiConfigNetworkListRefreshGuid = WIFI_CONFIG_NETWORK_LIST_REFRESH_G
EFI_GUID mWifiConfigConnectFormRefreshGuid = WIFI_CONFIG_CONNECT_FORM_REFRESH_GUID;
EFI_GUID mWifiConfigMainFormRefreshGuid = WIFI_CONFIG_MAIN_FORM_REFRESH_GUID;

+//
+// Wifi connection attempt counter for retries // extern UINT8
+mWifiConnectionCount;
+
/**
Tests to see if this driver supports a given controller. If a child device is provided,
it further tests to see if this driver supports creating a handle for the specified child device.
@@ -167,8 +172,10 @@ WifiMgrDxeDriverBindingStart (
EFI_WIRELESS_MAC_CONNECTION_II_PROTOCOL *Wmp;
EFI_SUPPLICANT_PROTOCOL *Supplicant;
EFI_EAP_CONFIGURATION_PROTOCOL *EapConfig;
+ EFI_WIFI_PROFILE_SYNC_PROTOCOL *WiFiProfileSyncProtocol;

- Nic = NULL;
+ mWifiConnectionCount = 0;
+ Nic = NULL;

//
// Open Protocols
@@ -236,47 +243,73 @@ WifiMgrDxeDriverBindingStart (
InitializeListHead (&Nic->ProfileList);

//
- // Record the MAC address of the incoming NIC.
+ // WiFi profile sync protocol installation check for OS recovery flow.
//
- Status = NetLibGetMacAddress (
- ControllerHandle,
- (EFI_MAC_ADDRESS *)&Nic->MacAddress,
- &AddressSize
- );
- if (EFI_ERROR (Status)) {
- goto ERROR2;
- }
-
- //
- // Create and start the timer for the status check
- //
- Status = gBS->CreateEvent (
- EVT_NOTIFY_SIGNAL | EVT_TIMER,
- TPL_CALLBACK,
- WifiMgrOnTimerTick,
- Nic,
- &Nic->TickTimer
+ Status = gBS->LocateProtocol (
+ &gEfiWiFiProfileSyncProtocolGuid,
+ NULL,
+ (VOID **)&WiFiProfileSyncProtocol
);
- if (EFI_ERROR (Status)) {
- goto ERROR2;
- }
+ if (!EFI_ERROR (Status)) {
+ Nic->ConnectPendingNetwork = (WIFI_MGR_NETWORK_PROFILE *)AllocateZeroPool (sizeof (WIFI_MGR_NETWORK_PROFILE));
+ if (Nic->ConnectPendingNetwork == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ goto ERROR1;
+ }

- Status = gBS->SetTimer (Nic->TickTimer, TimerPeriodic, EFI_TIMER_PERIOD_MILLISECONDS (500));
- if (EFI_ERROR (Status)) {
- goto ERROR3;
- }
+ WiFiProfileSyncProtocol->WifiProfileSyncGetProfile (Nic->ConnectPendingNetwork, Nic->MacAddress);
+ if (Nic->ConnectPendingNetwork != NULL) {
+ Status = WifiMgrConnectToNetwork (Nic, Nic->ConnectPendingNetwork);
+ if (EFI_ERROR (Status)) {
+ WiFiProfileSyncProtocol->WifiProfileSyncSetConnectState (Status);
+ }
+ } else {
+ goto ERROR1;
+ }
+ } else {
+ //
+ // Record the MAC address of the incoming NIC.
+ //
+ Status = NetLibGetMacAddress (
+ ControllerHandle,
+ (EFI_MAC_ADDRESS *)&Nic->MacAddress,
+ &AddressSize
+ );
+ if (EFI_ERROR (Status)) {
+ goto ERROR2;
+ }

- Nic->ConnectState = WifiMgrDisconnected;
- Nic->ScanState = WifiMgrScanFinished;
+ //
+ // Create and start the timer for the status check
+ //
+ Status = gBS->CreateEvent (
+ EVT_NOTIFY_SIGNAL | EVT_TIMER,
+ TPL_CALLBACK,
+ WifiMgrOnTimerTick,
+ Nic,
+ &Nic->TickTimer
+ );
+ if (EFI_ERROR (Status)) {
+ goto ERROR2;
+ }

- OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
- InsertTailList (&mPrivate->NicList, &Nic->Link);
- Nic->NicIndex = mPrivate->NicCount++;
- if (mPrivate->CurrentNic == NULL) {
- mPrivate->CurrentNic = Nic;
- }
+ Status = gBS->SetTimer (Nic->TickTimer, TimerPeriodic, EFI_TIMER_PERIOD_MILLISECONDS (500));
+ if (EFI_ERROR (Status)) {
+ goto ERROR3;
+ }

- gBS->RestoreTPL (OldTpl);
+ Nic->ConnectState = WifiMgrDisconnected;
+ Nic->ScanState = WifiMgrScanFinished;
+
+ OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
+ InsertTailList (&mPrivate->NicList, &Nic->Link);
+ Nic->NicIndex = mPrivate->NicCount++;
+ if (mPrivate->CurrentNic == NULL) {
+ mPrivate->CurrentNic = Nic;
+ }
+
+ gBS->RestoreTPL (OldTpl);
+ }

Status = gBS->InstallProtocolInterface (
&ControllerHandle,
@@ -385,10 +418,11 @@ WifiMgrDxeDriverBindingStop (
IN EFI_HANDLE *ChildHandleBuffer OPTIONAL
)
{
- EFI_STATUS Status;
- EFI_TPL OldTpl;
- WIFI_MGR_PRIVATE_PROTOCOL *WifiMgrIdentifier;
- WIFI_MGR_DEVICE_DATA *Nic;
+ EFI_STATUS Status;
+ EFI_TPL OldTpl;
+ WIFI_MGR_PRIVATE_PROTOCOL *WifiMgrIdentifier;
+ WIFI_MGR_DEVICE_DATA *Nic;
+ EFI_WIFI_PROFILE_SYNC_PROTOCOL *WiFiProfileSyncProtocol;

Status = gBS->OpenProtocol (
ControllerHandle,
@@ -481,7 +515,15 @@ WifiMgrDxeDriverBindingStop (
//
OldTpl = gBS->RaiseTPL (TPL_CALLBACK);

- RemoveEntryList (&Nic->Link);
+ Status = gBS->LocateProtocol (
+ &gEfiWiFiProfileSyncProtocolGuid,
+ NULL,
+ (VOID **)&WiFiProfileSyncProtocol
+ );
+ if (EFI_ERROR (Status)) {
+ RemoveEntryList (&Nic->Link);
+ }
+
mPrivate->NicCount--;
if (mPrivate->CurrentNic == Nic) {
mPrivate->CurrentNic = NULL;
diff --git a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDxe.h b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDxe.h
index 7b2e41e155..047f85dbc2 100644
--- a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDxe.h
+++ b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDxe.h
@@ -47,6 +47,7 @@
#include <Protocol/SimpleNetwork.h>
#include <Protocol/SimpleFileSystem.h>
#include <Protocol/EapConfiguration.h>
+#include <Protocol/WiFiProfileSyncProtocol.h>

//
// Produced Protocols
@@ -73,7 +74,8 @@
//
#define WIFI_MGR_DXE_VERSION 0xb

-#define OUI_IEEE_80211I 0xAC0F00
+#define OUI_IEEE_80211I 0xAC0F00
+#define MAX_WIFI_CONNETION_ATTEMPTS 3

typedef enum {
Ieee80211PairwiseCipherSuiteUseGroupCipherSuite = 0, diff --git a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrImpl.c b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrImpl.c
index 59bac48c42..a73ab9f710 100644
--- a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrImpl.c
+++ b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrImpl.c
@@ -19,6 +19,8 @@ EFI_EAP_TYPE mEapSecondAuthMethod[] = {
EFI_EAP_TYPE_MSCHAPV2
};

+UINT8 mWifiConnectionCount = 0;
+
/**
The callback function for scan operation. This function updates networks
according to the latest scan result, and trigger UI refresh.
@@ -424,18 +426,26 @@ WifiMgrConfigPassword (
return EFI_NOT_FOUND;
}

- AsciiPassword = AllocateZeroPool ((StrLen (Profile->Password) + 1) * sizeof (UINT8));
+ if (StrLen (Profile->Password) >= PASSWORD_STORAGE_SIZE) {
+ ASSERT (EFI_INVALID_PARAMETER);
+ return EFI_INVALID_PARAMETER;
+ }
+
+ AsciiPassword = AllocateZeroPool ((StrLen (Profile->Password) + 1) *
+ sizeof (CHAR8));
if (AsciiPassword == NULL) {
return EFI_OUT_OF_RESOURCES;
}

- UnicodeStrToAsciiStrS (Profile->Password, (CHAR8 *)AsciiPassword, PASSWORD_STORAGE_SIZE);
- Status = Supplicant->SetData (
- Supplicant,
- EfiSupplicant80211PskPassword,
- AsciiPassword,
- (StrLen (Profile->Password) + 1) * sizeof (UINT8)
- );
+ Status = UnicodeStrToAsciiStrS (Profile->Password, (CHAR8
+ *)AsciiPassword, (StrLen (Profile->Password) + 1)); if (!EFI_ERROR (Status)) {
+ Status = Supplicant->SetData (
+ Supplicant,
+ EfiSupplicant80211PskPassword,
+ AsciiPassword,
+ (StrLen (Profile->Password) + 1) * sizeof (CHAR8)
+ );
+ }
+
ZeroMem (AsciiPassword, AsciiStrLen ((CHAR8 *)AsciiPassword) + 1);
FreePool (AsciiPassword);

@@ -466,6 +476,7 @@ WifiMgrConfigEap (
)
{
EFI_STATUS Status;
+ EFI_WIFI_PROFILE_SYNC_PROTOCOL *WiFiProfileSyncProtocol;
EFI_EAP_CONFIGURATION_PROTOCOL *EapConfig;
EFI_EAP_TYPE EapAuthMethod;
EFI_EAP_TYPE EapSecondAuthMethod;
@@ -567,7 +578,13 @@ WifiMgrConfigEap (
return EFI_OUT_OF_RESOURCES;
}

- UnicodeStrToAsciiStrS (Profile->EapIdentity, Identity, IdentitySize);
+ Status = gBS->LocateProtocol (&gEfiWiFiProfileSyncProtocolGuid, NULL, (VOID **)&WiFiProfileSyncProtocol);
+ if (!EFI_ERROR (Status)) {
+ CopyMem (Identity, &Profile->EapIdentity, IdentitySize);
+ } else {
+ UnicodeStrToAsciiStrS (Profile->EapIdentity, Identity, IdentitySize);
+ }
+
Status = EapConfig->SetData (
EapConfig,
EFI_EAP_TYPE_IDENTITY, @@ -892,6 +909,133 @@ WifiMgrPrepareConnection (
return EFI_SUCCESS;
}

+/**
+ Will reset NiC data, get profile from profile sync driver, and send
+for
+ another connection attempt.This function should not be called more
+than
+ 3 times.
+
+ @param[in] WiFiProfileSyncProtocol The target network profile to connect.
+
+ @retval EFI_SUCCESS The operation is completed.
+ @retval other Operation failure.
+
+**/
+EFI_STATUS
+ConnectionRetry (
+ IN EFI_WIFI_PROFILE_SYNC_PROTOCOL *WiFiProfileSyncProtocol
+ )
+{
+ EFI_STATUS Status;
+ WIFI_MGR_DEVICE_DATA *Nic;
+ EFI_WIRELESS_MAC_CONNECTION_II_PROTOCOL *Wmp;
+ EFI_SUPPLICANT_PROTOCOL *Supplicant;
+ EFI_EAP_CONFIGURATION_PROTOCOL *EapConfig;
+
+ Nic = NULL;
+
+ Status = gBS->LocateProtocol (
+ &gEfiWiFi2ProtocolGuid,
+ NULL,
+ (VOID **)&Wmp
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ Status = gBS->LocateProtocol (
+ &gEfiSupplicantProtocolGuid,
+ NULL,
+ (VOID **)&Supplicant
+ );
+ if (EFI_ERROR (Status)) {
+ Supplicant = NULL;
+ }
+
+ Status = gBS->LocateProtocol (
+ &gEfiEapConfigurationProtocolGuid,
+ NULL,
+ (VOID **)&EapConfig
+ );
+ if (EFI_ERROR (Status)) {
+ EapConfig = NULL;
+ }
+
+ //
+ // Initialize Nic device data
+ //
+ Nic = AllocateZeroPool (sizeof (WIFI_MGR_DEVICE_DATA)); if (Nic ==
+ NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ return Status;
+ }
+
+ Nic->Signature = WIFI_MGR_DEVICE_DATA_SIGNATURE;
+ Nic->Private = mPrivate;
+ Nic->Wmp = Wmp;
+ Nic->Supplicant = Supplicant;
+ Nic->EapConfig = EapConfig;
+ Nic->UserSelectedProfile = NULL;
+ Nic->OneTimeScanRequest = FALSE;
+
+ if (Nic->Supplicant != NULL) {
+ Status = WifiMgrGetSupportedSuites (Nic); }
+
+ if (!EFI_ERROR (Status)) {
+ InitializeListHead (&Nic->ProfileList);
+
+ Nic->ConnectPendingNetwork = (WIFI_MGR_NETWORK_PROFILE *)AllocateZeroPool (sizeof (WIFI_MGR_NETWORK_PROFILE));
+ if (Nic->ConnectPendingNetwork == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ DEBUG ((DEBUG_ERROR, "[WiFi Connection Manager] Failed to allocate memory for ConnectPendingNetwork\n"));
+ goto ERROR;
+ }
+
+ Status = WiFiProfileSyncProtocol->WifiProfileSyncGetProfile (Nic->ConnectPendingNetwork, Nic->MacAddress);
+ if (!EFI_ERROR (Status) && (Nic->ConnectPendingNetwork != NULL)) {
+ Status = WifiMgrConnectToNetwork (Nic, Nic->ConnectPendingNetwork);
+ if (!EFI_ERROR (Status)) {
+ return Status;
+ }
+ } else {
+ DEBUG ((DEBUG_ERROR, "[WiFi Connection Manager] Failed to get WiFi profile with status %r\n", Status));
+ }
+ } else {
+ DEBUG ((DEBUG_ERROR, "[WiFi Connection Manager] Failed to get
+ Supported suites with status %r\n", Status)); }
+
+ if (Nic->ConnectPendingNetwork != NULL) {
+ if (Nic->ConnectPendingNetwork->Network.AKMSuite != NULL) {
+ FreePool (Nic->ConnectPendingNetwork->Network.AKMSuite);
+ }
+
+ if (Nic->ConnectPendingNetwork->Network.CipherSuite != NULL) {
+ FreePool (Nic->ConnectPendingNetwork->Network.CipherSuite);
+ }
+
+ FreePool (Nic->ConnectPendingNetwork); }
+
+ERROR:
+ if (Nic->Supplicant != NULL) {
+ if (Nic->SupportedSuites.SupportedAKMSuites != NULL) {
+ FreePool (Nic->SupportedSuites.SupportedAKMSuites);
+ }
+
+ if (Nic->SupportedSuites.SupportedSwCipherSuites != NULL) {
+ FreePool (Nic->SupportedSuites.SupportedSwCipherSuites);
+ }
+
+ if (Nic->SupportedSuites.SupportedHwCipherSuites != NULL) {
+ FreePool (Nic->SupportedSuites.SupportedHwCipherSuites);
+ }
+ }
+
+ FreePool (Nic);
+
+ return Status;
+}
+
/**
The callback function for connect operation.

@@ -908,12 +1052,13 @@ WifiMgrOnConnectFinished (
IN VOID *Context
)
{
- EFI_STATUS Status;
- WIFI_MGR_MAC_CONFIG_TOKEN *ConfigToken;
- WIFI_MGR_NETWORK_PROFILE *ConnectedProfile;
- UINT8 SecurityType;
- UINT8 SSIdLen;
- CHAR8 *AsciiSSId;
+ EFI_STATUS Status;
+ WIFI_MGR_MAC_CONFIG_TOKEN *ConfigToken;
+ WIFI_MGR_NETWORK_PROFILE *ConnectedProfile;
+ UINT8 SecurityType;
+ UINT8 SSIdLen;
+ CHAR8 *AsciiSSId;
+ EFI_WIFI_PROFILE_SYNC_PROTOCOL *WiFiProfileSyncProtocol;

ASSERT (Context != NULL);

@@ -925,6 +1070,24 @@ WifiMgrOnConnectFinished (
ASSERT (ConfigToken->Type == TokenTypeConnectNetworkToken);

ASSERT (ConfigToken->Token.ConnectNetworkToken != NULL);
+
+ Status = gBS->LocateProtocol (&gEfiWiFiProfileSyncProtocolGuid, NULL,
+ (VOID **)&WiFiProfileSyncProtocol); if (!EFI_ERROR (Status)) {
+ WiFiProfileSyncProtocol->WifiProfileSyncSetConnectState (ConfigToken->Token.ConnectNetworkToken->ResultCode);
+ if ((mWifiConnectionCount < MAX_WIFI_CONNETION_ATTEMPTS) &&
+ (ConfigToken->Token.ConnectNetworkToken->ResultCode != ConnectSuccess))
+ {
+ mWifiConnectionCount++;
+ gBS->CloseEvent (Event);
+ Status = ConnectionRetry (WiFiProfileSyncProtocol);
+ if (!EFI_ERROR (Status)) {
+ return;
+ }
+
+ WiFiProfileSyncProtocol->WifiProfileSyncSetConnectState (Status);
+ }
+ }
+
if (ConfigToken->Token.ConnectNetworkToken->Status != EFI_SUCCESS) {
if (ConfigToken->Nic->OneTimeConnectRequest) {
//
diff --git a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrMisc.c b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrMisc.c
index 4ad5643c24..87adfc5033 100644
--- a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrMisc.c
+++ b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrMisc.c
@@ -672,10 +672,23 @@ WifiMgrCleanProfileSecrets (
IN WIFI_MGR_NETWORK_PROFILE *Profile
)
{
+ EFI_STATUS Status;
+ EFI_WIFI_PROFILE_SYNC_PROTOCOL *WiFiProfileSyncProtocol;
+
ZeroMem (Profile->Password, sizeof (CHAR16) * PASSWORD_STORAGE_SIZE);
ZeroMem (Profile->EapPassword, sizeof (CHAR16) * PASSWORD_STORAGE_SIZE);
ZeroMem (Profile->PrivateKeyPassword, sizeof (CHAR16) * PASSWORD_STORAGE_SIZE);

+ //
+ // When EFI WiFi profile sync protocol is found the system is
+ performing a recovery boot in secure // boot mode. The profile sync
+ driver will manage the CA certificate, client certificate, and key // data, cleaning them at exit boot services.
+ //
+ Status = gBS->LocateProtocol (&gEfiWiFiProfileSyncProtocolGuid, NULL,
+ (VOID **)&WiFiProfileSyncProtocol); if (!EFI_ERROR (Status)) {
+ return;
+ }
+
if (Profile->CACertData != NULL) {
ZeroMem (Profile->CACertData, Profile->CACertSize);
FreePool (Profile->CACertData);
--
2.37.3.windows.1


Re: [PATCH v4] NetworkPkg/WifiProfileSync: Add WiFi profile sync protocol support

Clark-williams, Zachary
 

Thanks for the forward Mike!

Maciej and All,

If you could please review the PR below. I would like to get this review completed within the week.

Thanks,
Zack

-----Original Message-----
From: Kinney, Michael D <michael.d.kinney@...>
Sent: Thursday, October 27, 2022 1:09 PM
To: Rabeda, Maciej <maciej.rabeda@...>; Kinney, Michael D <michael.d.kinney@...>; Clark-williams, Zachary <zachary.clark-williams@...>
Subject: FW: [PATCH v4] NetworkPkg/WifiProfileSync: Add WiFi profile sync protocol support

Hi Maciej,

Can you please help review these NetworkPkg changes.

I am not sure if you monitor your linux.intel.com account as closely as your intel.com account.

Thanks,

Mike

-----Original Message-----
From: Clark-williams, Zachary <zachary.clark-williams@...>
Sent: Thursday, October 27, 2022 12:33 PM
To: Kinney, Michael D <michael.d.kinney@...>
Subject: FW: [PATCH v4] NetworkPkg/WifiProfileSync: Add WiFi profile sync protocol support

Hey Mike,

I'm struggling to get any feedback on this PR. Do you have any suggestions to get better visibility and responses so I can get this miving?

Thanks,
Zack

-----Original Message-----
From: Clark-williams, Zachary <zachary.clark-williams@...>
Sent: Thursday, October 27, 2022 12:31 PM
To: devel@edk2.groups.io
Cc: Zachary Clark-Williams <zclarkw112@...>; Maciej Rabeda <maciej.rabeda@...>; Fu Siyuan <siyuan.fu@...>; Wu, Jiaxin <jiaxin.wu@...>; Otcheretianski, Andrei <andrei.otcheretianski@...>; Clark-williams, Zachary <zachary.clark-williams@...>
Subject: [PATCH v4] NetworkPkg/WifiProfileSync: Add WiFi profile sync protocol support

From: Zachary Clark-Williams <zclarkw112@...>

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

Enables KVM and One Click Recovery WLAN capability with WiFi Profile Sync feature and protocol. Adding WiFiProfileSyncProtocol, which supports the profilesync driver operations for transferring WiFi profiles from AMT to the Supplicant. WiFiConnectionManager will check for the WifiProfileSyncProtocol and if found will operate on the premise of a One Click Recovery, or KVM flow with a Wifi profile provided by AMT.

Cc: Maciej Rabeda <maciej.rabeda@...>
Cc: Fu Siyuan <siyuan.fu@...>
Cc: Wu Jiaxin <jiaxin.wu@...>
Cc: Andrei Otcheretianski <andrei.otcheretianski@...>

Signed-off-by: Zachary Clark-Williams <zachary.clark-williams@...>
---
.../Protocol/WiFiProfileSyncProtocol.h | 83 ++++++++
NetworkPkg/NetworkPkg.dec | 3 +
.../WifiConnectionManagerDxe.inf | 3 +-
.../WifiConnectionMgrConfigNVDataStruct.h | 2 +-
.../WifiConnectionMgrDriver.c | 126 ++++++++----
.../WifiConnectionMgrDxe.h | 4 +-
.../WifiConnectionMgrImpl.c | 193 ++++++++++++++++--
.../WifiConnectionMgrMisc.c | 13 ++
8 files changed, 367 insertions(+), 60 deletions(-) create mode 100644 NetworkPkg/Include/Protocol/WiFiProfileSyncProtocol.h

diff --git a/NetworkPkg/Include/Protocol/WiFiProfileSyncProtocol.h b/NetworkPkg/Include/Protocol/WiFiProfileSyncProtocol.h
new file mode 100644
index 0000000000..e36daceabf
--- /dev/null
+++ b/NetworkPkg/Include/Protocol/WiFiProfileSyncProtocol.h
@@ -0,0 +1,83 @@
+/** @file
+ WiFi profile sync protocol. Supports One Click Recovery or KVM OS
+recovery
+ boot flow over WiFi.
+
+ Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent **/
+
+#ifndef WIFI_PROFILE_SYNC_PROTOCOL_H_
+#define WIFI_PROFILE_SYNC_PROTOCOL_H_
+
+#include <WifiConnectionManagerDxe/WifiConnectionMgrConfig.h>
+
+//
+// WiFi Profile Sync Protocol GUID variable.
+//
+extern EFI_GUID gEfiWiFiProfileSyncProtocolGuid;
+
+/**
+ Used by the WiFi connection manager to get the WiFi profile that AMT
+shared
+ and was stored in WiFi profile protocol. Aligns the AMT WiFi profile
+data to
+ the WiFi connection manager profile structure fo connection use.
+
+ @param[in, out] WcmProfile WiFi Connection Manager profile structure
+ @param[in, out] MacAddress MAC address from AMT saved to NiC MAC address
+
+ @retval EFI_SUCCESS Stored WiFi profile converted and returned succefully
+ @retval EFI_UNSUPPORTED Profile protocol sharing not supported or enabled
+ @retval EFI_NOT_FOUND No profiles to returned
+ @retval Others Error Occurred
+**/
+typedef
+EFI_STATUS
+(EFIAPI *WIFI_PROFILE_GET)(
+ IN OUT WIFI_MGR_NETWORK_PROFILE *Profile,
+ IN OUT EFI_80211_MAC_ADDRESS MacAddress
+ );
+
+/**
+ Saves the WiFi connection status recieved by the
+WiFiConnectionManager when
+ in a KVM OR One Click Recovery WLAN recovery flow. Input as
+ EFI_80211_CONNECT_NETWORK_RESULT_CODE then converted and stored as EFI_STATUS type.
+
+ @param[in] ConnectionStatus WiFi connection attempt results
+**/
+typedef
+VOID
+(EFIAPI *WIFI_SET_CONNECT_STATE)(
+ IN EFI_80211_CONNECT_NETWORK_RESULT_CODE ConnectionStatus
+ );
+
+/**
+ Retrieves the stored WiFi connection status when in either KVM OR One
+Click
+ Recovery WLAN recovery flow.
+
+ @retval EFI_SUCCESS WiFi connection completed succesfully
+ @retval Others Connection failure occurred
+**/
+typedef
+EFI_STATUS
+(EFIAPI *WIFI_GET_CONNECT_STATE)(
+ VOID
+ );
+
+//
+// WiFi Profile Sync Protocol structure.
+//
+typedef struct {
+ UINT32 Revision;
+ WIFI_SET_CONNECT_STATE WifiProfileSyncSetConnectState;
+ WIFI_GET_CONNECT_STATE WifiProfileSyncGetConnectState;
+ WIFI_PROFILE_GET WifiProfileSyncGetProfile;
+} EFI_WIFI_PROFILE_SYNC_PROTOCOL;
+
+/**
+ WiFi Profile Protocol revision number.
+
+ Revision 1: Initial version
+**/
+#define EFI_WIFI_PROFILE_SYNC_PROTOCOL_REVISION 1
+
+#endif // WIFI_PROFILE_SYNC_PROTOCOL_H_
diff --git a/NetworkPkg/NetworkPkg.dec b/NetworkPkg/NetworkPkg.dec index 5e43ebf8c5..53fb34c4a0 100644
--- a/NetworkPkg/NetworkPkg.dec
+++ b/NetworkPkg/NetworkPkg.dec
@@ -91,6 +91,9 @@
## Include/Protocol/HttpCallback.h
gEdkiiHttpCallbackProtocolGuid = {0x611114f1, 0xa37b, 0x4468, {0xa4, 0x36, 0x5b, 0xdd, 0xa1, 0x6a, 0xa2, 0x40}}

+ ## Include/Protocol/WiFiProfileSyncProtocol.h
+ gEfiWiFiProfileSyncProtocolGuid = {0x399a2b8a, 0xc267, 0x44aa, {0x9a,
+ 0xb4, 0x30, 0x58, 0x8c, 0xd2, 0x2d, 0xcc}}
+
[PcdsFixedAtBuild]
## The max attempt number will be created by iSCSI driver.
# @Prompt Max attempt number.
diff --git a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionManagerDxe.inf b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionManagerDxe.inf
index 4394b6f4bb..7e36016cf8 100644
--- a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionManagerDxe.inf
+++ b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionManagerDxe.inf
@@ -9,7 +9,7 @@
# 2). WPA2 Personal Network
# 3). EAP Networks (EAP-TLS, EAP-TTLS/MSCHAPv2 and PEAPv0/MSCHAPv2) # -# Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2019 - 2022, Intel Corporation. All rights
+reserved.<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -71,6 +71,7 @@
gEfiAdapterInformationProtocolGuid ## SOMETIMES_CONSUMES
gEfiSupplicantProtocolGuid ## SOMETIMES_CONSUMES
gEfiEapConfigurationProtocolGuid ## SOMETIMES_CONSUMES
+ gEfiWiFiProfileSyncProtocolGuid ## SOMETIMES_CONSUMES

[Guids]
gWifiConfigGuid ## PRODUCES ## GUID
diff --git a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrConfigNVDataStruct.h b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrConfigNVDataStruct.h
index b5518a74d8..dcc4bf7e27 100644
--- a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrConfigNVDataStruct.h
+++ b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrConfigNVDataS
+++ truct.h
@@ -25,7 +25,7 @@

#define PASSWORD_MIN_LEN 8
#define PASSWORD_MAX_LEN 63
-#define PASSWORD_STORAGE_SIZE 64
+#define PASSWORD_STORAGE_SIZE 65

#define EAP_IDENTITY_LEN 63
#define EAP_IDENTITY_SIZE 64
diff --git a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDriver.c b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDriver.c
index 67a01ca058..97ca7a9f0b 100644
--- a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDriver.c
+++ b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDriver.c
@@ -1,7 +1,7 @@
/** @file
The driver binding protocol for the WiFi Connection Manager.

- Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2019 - 2022, Intel Corporation. All rights
+ reserved.<BR>

SPDX-License-Identifier: BSD-2-Clause-Patent

@@ -39,6 +39,11 @@ EFI_GUID mWifiConfigNetworkListRefreshGuid = WIFI_CONFIG_NETWORK_LIST_REFRESH_G
EFI_GUID mWifiConfigConnectFormRefreshGuid = WIFI_CONFIG_CONNECT_FORM_REFRESH_GUID;
EFI_GUID mWifiConfigMainFormRefreshGuid = WIFI_CONFIG_MAIN_FORM_REFRESH_GUID;

+//
+// Wifi connection attempt counter for retries // extern UINT8
+mWifiConnectionCount;
+
/**
Tests to see if this driver supports a given controller. If a child device is provided,
it further tests to see if this driver supports creating a handle for the specified child device.
@@ -167,8 +172,10 @@ WifiMgrDxeDriverBindingStart (
EFI_WIRELESS_MAC_CONNECTION_II_PROTOCOL *Wmp;
EFI_SUPPLICANT_PROTOCOL *Supplicant;
EFI_EAP_CONFIGURATION_PROTOCOL *EapConfig;
+ EFI_WIFI_PROFILE_SYNC_PROTOCOL *WiFiProfileSyncProtocol;

- Nic = NULL;
+ mWifiConnectionCount = 0;
+ Nic = NULL;

//
// Open Protocols
@@ -236,47 +243,73 @@ WifiMgrDxeDriverBindingStart (
InitializeListHead (&Nic->ProfileList);

//
- // Record the MAC address of the incoming NIC.
+ // WiFi profile sync protocol installation check for OS recovery flow.
//
- Status = NetLibGetMacAddress (
- ControllerHandle,
- (EFI_MAC_ADDRESS *)&Nic->MacAddress,
- &AddressSize
- );
- if (EFI_ERROR (Status)) {
- goto ERROR2;
- }
-
- //
- // Create and start the timer for the status check
- //
- Status = gBS->CreateEvent (
- EVT_NOTIFY_SIGNAL | EVT_TIMER,
- TPL_CALLBACK,
- WifiMgrOnTimerTick,
- Nic,
- &Nic->TickTimer
+ Status = gBS->LocateProtocol (
+ &gEfiWiFiProfileSyncProtocolGuid,
+ NULL,
+ (VOID **)&WiFiProfileSyncProtocol
);
- if (EFI_ERROR (Status)) {
- goto ERROR2;
- }
+ if (!EFI_ERROR (Status)) {
+ Nic->ConnectPendingNetwork = (WIFI_MGR_NETWORK_PROFILE *)AllocateZeroPool (sizeof (WIFI_MGR_NETWORK_PROFILE));
+ if (Nic->ConnectPendingNetwork == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ goto ERROR1;
+ }

- Status = gBS->SetTimer (Nic->TickTimer, TimerPeriodic, EFI_TIMER_PERIOD_MILLISECONDS (500));
- if (EFI_ERROR (Status)) {
- goto ERROR3;
- }
+ WiFiProfileSyncProtocol->WifiProfileSyncGetProfile (Nic->ConnectPendingNetwork, Nic->MacAddress);
+ if (Nic->ConnectPendingNetwork != NULL) {
+ Status = WifiMgrConnectToNetwork (Nic, Nic->ConnectPendingNetwork);
+ if (EFI_ERROR (Status)) {
+ WiFiProfileSyncProtocol->WifiProfileSyncSetConnectState (Status);
+ }
+ } else {
+ goto ERROR1;
+ }
+ } else {
+ //
+ // Record the MAC address of the incoming NIC.
+ //
+ Status = NetLibGetMacAddress (
+ ControllerHandle,
+ (EFI_MAC_ADDRESS *)&Nic->MacAddress,
+ &AddressSize
+ );
+ if (EFI_ERROR (Status)) {
+ goto ERROR2;
+ }

- Nic->ConnectState = WifiMgrDisconnected;
- Nic->ScanState = WifiMgrScanFinished;
+ //
+ // Create and start the timer for the status check
+ //
+ Status = gBS->CreateEvent (
+ EVT_NOTIFY_SIGNAL | EVT_TIMER,
+ TPL_CALLBACK,
+ WifiMgrOnTimerTick,
+ Nic,
+ &Nic->TickTimer
+ );
+ if (EFI_ERROR (Status)) {
+ goto ERROR2;
+ }

- OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
- InsertTailList (&mPrivate->NicList, &Nic->Link);
- Nic->NicIndex = mPrivate->NicCount++;
- if (mPrivate->CurrentNic == NULL) {
- mPrivate->CurrentNic = Nic;
- }
+ Status = gBS->SetTimer (Nic->TickTimer, TimerPeriodic, EFI_TIMER_PERIOD_MILLISECONDS (500));
+ if (EFI_ERROR (Status)) {
+ goto ERROR3;
+ }

- gBS->RestoreTPL (OldTpl);
+ Nic->ConnectState = WifiMgrDisconnected;
+ Nic->ScanState = WifiMgrScanFinished;
+
+ OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
+ InsertTailList (&mPrivate->NicList, &Nic->Link);
+ Nic->NicIndex = mPrivate->NicCount++;
+ if (mPrivate->CurrentNic == NULL) {
+ mPrivate->CurrentNic = Nic;
+ }
+
+ gBS->RestoreTPL (OldTpl);
+ }

Status = gBS->InstallProtocolInterface (
&ControllerHandle,
@@ -385,10 +418,11 @@ WifiMgrDxeDriverBindingStop (
IN EFI_HANDLE *ChildHandleBuffer OPTIONAL
)
{
- EFI_STATUS Status;
- EFI_TPL OldTpl;
- WIFI_MGR_PRIVATE_PROTOCOL *WifiMgrIdentifier;
- WIFI_MGR_DEVICE_DATA *Nic;
+ EFI_STATUS Status;
+ EFI_TPL OldTpl;
+ WIFI_MGR_PRIVATE_PROTOCOL *WifiMgrIdentifier;
+ WIFI_MGR_DEVICE_DATA *Nic;
+ EFI_WIFI_PROFILE_SYNC_PROTOCOL *WiFiProfileSyncProtocol;

Status = gBS->OpenProtocol (
ControllerHandle,
@@ -481,7 +515,15 @@ WifiMgrDxeDriverBindingStop (
//
OldTpl = gBS->RaiseTPL (TPL_CALLBACK);

- RemoveEntryList (&Nic->Link);
+ Status = gBS->LocateProtocol (
+ &gEfiWiFiProfileSyncProtocolGuid,
+ NULL,
+ (VOID **)&WiFiProfileSyncProtocol
+ );
+ if (EFI_ERROR (Status)) {
+ RemoveEntryList (&Nic->Link);
+ }
+
mPrivate->NicCount--;
if (mPrivate->CurrentNic == Nic) {
mPrivate->CurrentNic = NULL;
diff --git a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDxe.h b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDxe.h
index 7b2e41e155..047f85dbc2 100644
--- a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDxe.h
+++ b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDxe.h
@@ -47,6 +47,7 @@
#include <Protocol/SimpleNetwork.h>
#include <Protocol/SimpleFileSystem.h>
#include <Protocol/EapConfiguration.h>
+#include <Protocol/WiFiProfileSyncProtocol.h>

//
// Produced Protocols
@@ -73,7 +74,8 @@
//
#define WIFI_MGR_DXE_VERSION 0xb

-#define OUI_IEEE_80211I 0xAC0F00
+#define OUI_IEEE_80211I 0xAC0F00
+#define MAX_WIFI_CONNETION_ATTEMPTS 3

typedef enum {
Ieee80211PairwiseCipherSuiteUseGroupCipherSuite = 0, diff --git a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrImpl.c b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrImpl.c
index 59bac48c42..a73ab9f710 100644
--- a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrImpl.c
+++ b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrImpl.c
@@ -19,6 +19,8 @@ EFI_EAP_TYPE mEapSecondAuthMethod[] = {
EFI_EAP_TYPE_MSCHAPV2
};

+UINT8 mWifiConnectionCount = 0;
+
/**
The callback function for scan operation. This function updates networks
according to the latest scan result, and trigger UI refresh.
@@ -424,18 +426,26 @@ WifiMgrConfigPassword (
return EFI_NOT_FOUND;
}

- AsciiPassword = AllocateZeroPool ((StrLen (Profile->Password) + 1) * sizeof (UINT8));
+ if (StrLen (Profile->Password) >= PASSWORD_STORAGE_SIZE) {
+ ASSERT (EFI_INVALID_PARAMETER);
+ return EFI_INVALID_PARAMETER;
+ }
+
+ AsciiPassword = AllocateZeroPool ((StrLen (Profile->Password) + 1) *
+ sizeof (CHAR8));
if (AsciiPassword == NULL) {
return EFI_OUT_OF_RESOURCES;
}

- UnicodeStrToAsciiStrS (Profile->Password, (CHAR8 *)AsciiPassword, PASSWORD_STORAGE_SIZE);
- Status = Supplicant->SetData (
- Supplicant,
- EfiSupplicant80211PskPassword,
- AsciiPassword,
- (StrLen (Profile->Password) + 1) * sizeof (UINT8)
- );
+ Status = UnicodeStrToAsciiStrS (Profile->Password, (CHAR8
+ *)AsciiPassword, (StrLen (Profile->Password) + 1)); if (!EFI_ERROR (Status)) {
+ Status = Supplicant->SetData (
+ Supplicant,
+ EfiSupplicant80211PskPassword,
+ AsciiPassword,
+ (StrLen (Profile->Password) + 1) * sizeof (CHAR8)
+ );
+ }
+
ZeroMem (AsciiPassword, AsciiStrLen ((CHAR8 *)AsciiPassword) + 1);
FreePool (AsciiPassword);

@@ -466,6 +476,7 @@ WifiMgrConfigEap (
)
{
EFI_STATUS Status;
+ EFI_WIFI_PROFILE_SYNC_PROTOCOL *WiFiProfileSyncProtocol;
EFI_EAP_CONFIGURATION_PROTOCOL *EapConfig;
EFI_EAP_TYPE EapAuthMethod;
EFI_EAP_TYPE EapSecondAuthMethod;
@@ -567,7 +578,13 @@ WifiMgrConfigEap (
return EFI_OUT_OF_RESOURCES;
}

- UnicodeStrToAsciiStrS (Profile->EapIdentity, Identity, IdentitySize);
+ Status = gBS->LocateProtocol (&gEfiWiFiProfileSyncProtocolGuid, NULL, (VOID **)&WiFiProfileSyncProtocol);
+ if (!EFI_ERROR (Status)) {
+ CopyMem (Identity, &Profile->EapIdentity, IdentitySize);
+ } else {
+ UnicodeStrToAsciiStrS (Profile->EapIdentity, Identity, IdentitySize);
+ }
+
Status = EapConfig->SetData (
EapConfig,
EFI_EAP_TYPE_IDENTITY, @@ -892,6 +909,133 @@ WifiMgrPrepareConnection (
return EFI_SUCCESS;
}

+/**
+ Will reset NiC data, get profile from profile sync driver, and send
+for
+ another connection attempt.This function should not be called more
+than
+ 3 times.
+
+ @param[in] WiFiProfileSyncProtocol The target network profile to connect.
+
+ @retval EFI_SUCCESS The operation is completed.
+ @retval other Operation failure.
+
+**/
+EFI_STATUS
+ConnectionRetry (
+ IN EFI_WIFI_PROFILE_SYNC_PROTOCOL *WiFiProfileSyncProtocol
+ )
+{
+ EFI_STATUS Status;
+ WIFI_MGR_DEVICE_DATA *Nic;
+ EFI_WIRELESS_MAC_CONNECTION_II_PROTOCOL *Wmp;
+ EFI_SUPPLICANT_PROTOCOL *Supplicant;
+ EFI_EAP_CONFIGURATION_PROTOCOL *EapConfig;
+
+ Nic = NULL;
+
+ Status = gBS->LocateProtocol (
+ &gEfiWiFi2ProtocolGuid,
+ NULL,
+ (VOID **)&Wmp
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ Status = gBS->LocateProtocol (
+ &gEfiSupplicantProtocolGuid,
+ NULL,
+ (VOID **)&Supplicant
+ );
+ if (EFI_ERROR (Status)) {
+ Supplicant = NULL;
+ }
+
+ Status = gBS->LocateProtocol (
+ &gEfiEapConfigurationProtocolGuid,
+ NULL,
+ (VOID **)&EapConfig
+ );
+ if (EFI_ERROR (Status)) {
+ EapConfig = NULL;
+ }
+
+ //
+ // Initialize Nic device data
+ //
+ Nic = AllocateZeroPool (sizeof (WIFI_MGR_DEVICE_DATA)); if (Nic ==
+ NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ return Status;
+ }
+
+ Nic->Signature = WIFI_MGR_DEVICE_DATA_SIGNATURE;
+ Nic->Private = mPrivate;
+ Nic->Wmp = Wmp;
+ Nic->Supplicant = Supplicant;
+ Nic->EapConfig = EapConfig;
+ Nic->UserSelectedProfile = NULL;
+ Nic->OneTimeScanRequest = FALSE;
+
+ if (Nic->Supplicant != NULL) {
+ Status = WifiMgrGetSupportedSuites (Nic); }
+
+ if (!EFI_ERROR (Status)) {
+ InitializeListHead (&Nic->ProfileList);
+
+ Nic->ConnectPendingNetwork = (WIFI_MGR_NETWORK_PROFILE *)AllocateZeroPool (sizeof (WIFI_MGR_NETWORK_PROFILE));
+ if (Nic->ConnectPendingNetwork == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ DEBUG ((DEBUG_ERROR, "[WiFi Connection Manager] Failed to allocate memory for ConnectPendingNetwork\n"));
+ goto ERROR;
+ }
+
+ Status = WiFiProfileSyncProtocol->WifiProfileSyncGetProfile (Nic->ConnectPendingNetwork, Nic->MacAddress);
+ if (!EFI_ERROR (Status) && (Nic->ConnectPendingNetwork != NULL)) {
+ Status = WifiMgrConnectToNetwork (Nic, Nic->ConnectPendingNetwork);
+ if (!EFI_ERROR (Status)) {
+ return Status;
+ }
+ } else {
+ DEBUG ((DEBUG_ERROR, "[WiFi Connection Manager] Failed to get WiFi profile with status %r\n", Status));
+ }
+ } else {
+ DEBUG ((DEBUG_ERROR, "[WiFi Connection Manager] Failed to get
+ Supported suites with status %r\n", Status)); }
+
+ if (Nic->ConnectPendingNetwork != NULL) {
+ if (Nic->ConnectPendingNetwork->Network.AKMSuite != NULL) {
+ FreePool (Nic->ConnectPendingNetwork->Network.AKMSuite);
+ }
+
+ if (Nic->ConnectPendingNetwork->Network.CipherSuite != NULL) {
+ FreePool (Nic->ConnectPendingNetwork->Network.CipherSuite);
+ }
+
+ FreePool (Nic->ConnectPendingNetwork); }
+
+ERROR:
+ if (Nic->Supplicant != NULL) {
+ if (Nic->SupportedSuites.SupportedAKMSuites != NULL) {
+ FreePool (Nic->SupportedSuites.SupportedAKMSuites);
+ }
+
+ if (Nic->SupportedSuites.SupportedSwCipherSuites != NULL) {
+ FreePool (Nic->SupportedSuites.SupportedSwCipherSuites);
+ }
+
+ if (Nic->SupportedSuites.SupportedHwCipherSuites != NULL) {
+ FreePool (Nic->SupportedSuites.SupportedHwCipherSuites);
+ }
+ }
+
+ FreePool (Nic);
+
+ return Status;
+}
+
/**
The callback function for connect operation.

@@ -908,12 +1052,13 @@ WifiMgrOnConnectFinished (
IN VOID *Context
)
{
- EFI_STATUS Status;
- WIFI_MGR_MAC_CONFIG_TOKEN *ConfigToken;
- WIFI_MGR_NETWORK_PROFILE *ConnectedProfile;
- UINT8 SecurityType;
- UINT8 SSIdLen;
- CHAR8 *AsciiSSId;
+ EFI_STATUS Status;
+ WIFI_MGR_MAC_CONFIG_TOKEN *ConfigToken;
+ WIFI_MGR_NETWORK_PROFILE *ConnectedProfile;
+ UINT8 SecurityType;
+ UINT8 SSIdLen;
+ CHAR8 *AsciiSSId;
+ EFI_WIFI_PROFILE_SYNC_PROTOCOL *WiFiProfileSyncProtocol;

ASSERT (Context != NULL);

@@ -925,6 +1070,24 @@ WifiMgrOnConnectFinished (
ASSERT (ConfigToken->Type == TokenTypeConnectNetworkToken);

ASSERT (ConfigToken->Token.ConnectNetworkToken != NULL);
+
+ Status = gBS->LocateProtocol (&gEfiWiFiProfileSyncProtocolGuid, NULL,
+ (VOID **)&WiFiProfileSyncProtocol); if (!EFI_ERROR (Status)) {
+ WiFiProfileSyncProtocol->WifiProfileSyncSetConnectState (ConfigToken->Token.ConnectNetworkToken->ResultCode);
+ if ((mWifiConnectionCount < MAX_WIFI_CONNETION_ATTEMPTS) &&
+ (ConfigToken->Token.ConnectNetworkToken->ResultCode != ConnectSuccess))
+ {
+ mWifiConnectionCount++;
+ gBS->CloseEvent (Event);
+ Status = ConnectionRetry (WiFiProfileSyncProtocol);
+ if (!EFI_ERROR (Status)) {
+ return;
+ }
+
+ WiFiProfileSyncProtocol->WifiProfileSyncSetConnectState (Status);
+ }
+ }
+
if (ConfigToken->Token.ConnectNetworkToken->Status != EFI_SUCCESS) {
if (ConfigToken->Nic->OneTimeConnectRequest) {
//
diff --git a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrMisc.c b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrMisc.c
index 4ad5643c24..87adfc5033 100644
--- a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrMisc.c
+++ b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrMisc.c
@@ -672,10 +672,23 @@ WifiMgrCleanProfileSecrets (
IN WIFI_MGR_NETWORK_PROFILE *Profile
)
{
+ EFI_STATUS Status;
+ EFI_WIFI_PROFILE_SYNC_PROTOCOL *WiFiProfileSyncProtocol;
+
ZeroMem (Profile->Password, sizeof (CHAR16) * PASSWORD_STORAGE_SIZE);
ZeroMem (Profile->EapPassword, sizeof (CHAR16) * PASSWORD_STORAGE_SIZE);
ZeroMem (Profile->PrivateKeyPassword, sizeof (CHAR16) * PASSWORD_STORAGE_SIZE);

+ //
+ // When EFI WiFi profile sync protocol is found the system is
+ performing a recovery boot in secure // boot mode. The profile sync
+ driver will manage the CA certificate, client certificate, and key // data, cleaning them at exit boot services.
+ //
+ Status = gBS->LocateProtocol (&gEfiWiFiProfileSyncProtocolGuid, NULL,
+ (VOID **)&WiFiProfileSyncProtocol); if (!EFI_ERROR (Status)) {
+ return;
+ }
+
if (Profile->CACertData != NULL) {
ZeroMem (Profile->CACertData, Profile->CACertSize);
FreePool (Profile->CACertData);
--
2.37.3.windows.1


[Patch 1/1] CryptoPkg/Test: Simplify BaseCryptLib host based unit tests

Michael D Kinney
 

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

Remove TestBaseCryptLibHostAccel.inf and instead use FILE_GUID
override in DSC file to run the same unit test INF against
OpensslLibFull.inf and OpensslLibFullAccel.inf

Cc: Jiewen Yao <jiewen.yao@...>
Cc: Jian J Wang <jian.j.wang@...>
Cc: Xiaoyu Lu <xiaoyu1.lu@...>
Cc: Guomin Jiang <guomin.jiang@...>
Signed-off-by: Michael D Kinney <michael.d.kinney@...>
---
CryptoPkg/Test/CryptoPkgHostUnitTest.dsc | 10 +++-
.../TestBaseCryptLibHostAccel.inf | 56 -------------------
2 files changed, 7 insertions(+), 59 deletions(-)
delete mode 100644 CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHostAccel.inf

diff --git a/CryptoPkg/Test/CryptoPkgHostUnitTest.dsc b/CryptoPkg/Test/CryptoPkgHostUnitTest.dsc
index 369a1cb69939..3ed3e9b75d84 100644
--- a/CryptoPkg/Test/CryptoPkgHostUnitTest.dsc
+++ b/CryptoPkg/Test/CryptoPkgHostUnitTest.dsc
@@ -20,7 +20,6 @@ [Defines]
!include UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc

[LibraryClasses]
- OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFull.inf
BaseCryptLib|CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf
MmServicesTableLib|MdePkg/Library/MmServicesTableLib/MmServicesTableLib.inf
SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf
@@ -33,8 +32,13 @@ [Components]
#
# Build HOST_APPLICATION that tests the SampleUnitTest
#
- CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf
- CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHostAccel.inf {
+ CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf {
+ <LibraryClasses>
+ OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFull.inf
+ }
+ CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf {
+ <Defines>
+ FILE_GUID = 3604CCB8-138C-488F-8045-18704F73E734
<LibraryClasses>
OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf
}
diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHostAccel.inf b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHostAccel.inf
deleted file mode 100644
index 9d0fcfd3577c..000000000000
--- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHostAccel.inf
+++ /dev/null
@@ -1,56 +0,0 @@
-## @file
-# Host-based UnitTest for BaseCryptLib
-#
-# Copyright (c) Microsoft Corporation.<BR>
-# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>
-# SPDX-License-Identifier: BSD-2-Clause-Patent
-##
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = BaseCryptLibUnitTestHostAccel
- FILE_GUID = B1AED64E-B53A-4D69-B0BA-60EEDAC47A6B
- MODULE_TYPE = HOST_APPLICATION
- VERSION_STRING = 1.0
-
-#
-# The following information is for reference only and not required by the build tools.
-#
-# VALID_ARCHITECTURES = IA32 X64
-#
-
-[Sources]
- UnitTestMain.c
- BaseCryptLibUnitTests.c
- TestBaseCryptLib.h
- HashTests.c
- HmacTests.c
- BlockCipherTests.c
- RsaTests.c
- RsaPkcs7Tests.c
- Pkcs5Pbkdf2Tests.c
- AuthenticodeTests.c
- TSTests.c
- DhTests.c
- RandTests.c
- Pkcs7EkuTests.c
- OaepEncryptTests.c
- RsaPssTests.c
- ParallelhashTests.c
- HkdfTests.c
- AeadAesGcmTests.c
- BnTests.c
- EcTests.c
- X509Tests.c
-
-[Packages]
- MdePkg/MdePkg.dec
- CryptoPkg/CryptoPkg.dec
-
-[LibraryClasses]
- BaseLib
- DebugLib
- BaseCryptLib
- UnitTestLib
- MmServicesTableLib
- SynchronizationLib
--
2.37.1.windows.1