public inbox for devel@edk2.groups.io
 help / color / mirror / Atom feed
* [edk2-devel] [PATCH v1 02/29] MdePkg: Add LoongArch64 FPU function set into BaseCpuLib
       [not found] <20231102134249.3983594-1-lichao@loongson.cn>
@ 2023-11-02 13:42 ` Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 03/29] MdePkg: Add LoongArch64 exception function set into BaseLib Chao Li
                   ` (16 subsequent siblings)
  17 siblings, 0 replies; 18+ messages in thread
From: Chao Li @ 2023-11-02 13:42 UTC (permalink / raw)
  To: devel; +Cc: Michael D Kinney, Liming Gao, Zhiguang Liu

Adding InitializeFloatingPointUnits, EnableFloatingPointUnits and
DisableFloatingPointUnits functions for LoongArch64.

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

Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
Cc: Zhiguang Liu <zhiguang.liu@intel.com>
Signed-off-by: Chao Li <lichao@loongson.cn>
---
 MdePkg/Include/Library/CpuLib.h               | 37 +++++++++++---
 MdePkg/Library/BaseCpuLib/BaseCpuLib.inf      |  7 ++-
 .../Library/BaseCpuLib/LoongArch/DisableFpu.S | 17 +++++++
 .../Library/BaseCpuLib/LoongArch/EnableFpu.S  | 17 +++++++
 .../BaseCpuLib/LoongArch/InitializeFpu.S      | 51 +++++++++++++++++++
 5 files changed, 121 insertions(+), 8 deletions(-)
 create mode 100644 MdePkg/Library/BaseCpuLib/LoongArch/DisableFpu.S
 create mode 100644 MdePkg/Library/BaseCpuLib/LoongArch/EnableFpu.S
 create mode 100644 MdePkg/Library/BaseCpuLib/LoongArch/InitializeFpu.S

diff --git a/MdePkg/Include/Library/CpuLib.h b/MdePkg/Include/Library/CpuLib.h
index 3f29937dc7..42da55ca69 100644
--- a/MdePkg/Include/Library/CpuLib.h
+++ b/MdePkg/Include/Library/CpuLib.h
@@ -8,6 +8,7 @@
   As a result, these services could not be defined in the Base Library.
 
 Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2023, Loongson Technology Corporation Limited. All rights reserved.<BR>
 SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
@@ -41,14 +42,14 @@ CpuFlushTlb (
   VOID
   );
 
-#if defined (MDE_CPU_IA32) || defined (MDE_CPU_X64)
-
 /**
+  Initialize the CPU floating point units.
+
   Initializes floating point units for requirement of UEFI specification.
-  This function initializes floating-point control word to 0x027F (all exceptions
-  masked,double-precision, round-to-nearest) and multimedia-extensions control word
-  (if supported) to 0x1F80 (all exceptions masked, round-to-nearest, flush to zero
-  for masked underflow).
+  For IA32 and X64, this function initializes floating-point control word to 0x027F
+  (all exceptions masked,double-precision, round-to-nearest) and multimedia-extensions
+  control word (if supported) to 0x1F80 (all exceptions masked, round-to-nearest,
+  flush to zero for masked underflow).
 **/
 VOID
 EFIAPI
@@ -56,6 +57,30 @@ InitializeFloatingPointUnits (
   VOID
   );
 
+/**
+  Enable the CPU floating point units.
+
+  Enable the CPU floating point units.
+**/
+VOID
+EFIAPI
+EnableFloatingPointUnits (
+  VOID
+  );
+
+/**
+  Disable the CPU floating point units.
+
+  Disable the CPU floating point units.
+**/
+VOID
+EFIAPI
+DisableFloatingPointUnits (
+  VOID
+  );
+
+#if defined (MDE_CPU_IA32) || defined (MDE_CPU_X64)
+
 /**
   Determine if the standard CPU signature is "AuthenticAMD".
   @retval TRUE  The CPU signature matches.
diff --git a/MdePkg/Library/BaseCpuLib/BaseCpuLib.inf b/MdePkg/Library/BaseCpuLib/BaseCpuLib.inf
index 9a162afe6d..89f6272f11 100644
--- a/MdePkg/Library/BaseCpuLib/BaseCpuLib.inf
+++ b/MdePkg/Library/BaseCpuLib/BaseCpuLib.inf
@@ -65,8 +65,11 @@
   RiscV/Cpu.S
 
 [Sources.LOONGARCH64]
-  LoongArch/CpuFlushTlb.S | GCC
-  LoongArch/CpuSleep.S    | GCC
+  LoongArch/CpuFlushTlb.S   | GCC
+  LoongArch/CpuSleep.S      | GCC
+  LoongArch/InitializeFpu.S | GCC
+  LoongArch/EnableFpu.S     | GCC
+  LoongArch/DisableFpu.S    | GCC
 
 [Packages]
   MdePkg/MdePkg.dec
diff --git a/MdePkg/Library/BaseCpuLib/LoongArch/DisableFpu.S b/MdePkg/Library/BaseCpuLib/LoongArch/DisableFpu.S
new file mode 100644
index 0000000000..6cb253a416
--- /dev/null
+++ b/MdePkg/Library/BaseCpuLib/LoongArch/DisableFpu.S
@@ -0,0 +1,17 @@
+#------------------------------------------------------------------------------
+#
+# DisableFloatingPointUnits() for LoongArch64
+#
+# Copyright (c) 2023, Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#------------------------------------------------------------------------------
+ASM_GLOBAL ASM_PFX(DisableFloatingPointUnits)
+
+ASM_PFX(DisableFloatingPointUnits):
+  li.w        $t0, 0x1
+  csrxchg     $zero, $t0, 0x2
+
+  jirl $zero, $ra, 0
+  .end
diff --git a/MdePkg/Library/BaseCpuLib/LoongArch/EnableFpu.S b/MdePkg/Library/BaseCpuLib/LoongArch/EnableFpu.S
new file mode 100644
index 0000000000..27d8243a59
--- /dev/null
+++ b/MdePkg/Library/BaseCpuLib/LoongArch/EnableFpu.S
@@ -0,0 +1,17 @@
+#------------------------------------------------------------------------------
+#
+# EnableFloatingPointUnits() for LoongArch64
+#
+# Copyright (c) 2023, Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#------------------------------------------------------------------------------
+ASM_GLOBAL ASM_PFX(EnableFloatingPointUnits)
+
+ASM_PFX(EnableFloatingPointUnits):
+  li.w        $t0, 0x1
+  csrxchg     $t0, $t0, 0x2
+
+  jirl $zero, $ra, 0
+  .end
diff --git a/MdePkg/Library/BaseCpuLib/LoongArch/InitializeFpu.S b/MdePkg/Library/BaseCpuLib/LoongArch/InitializeFpu.S
new file mode 100644
index 0000000000..1b9d01c2c1
--- /dev/null
+++ b/MdePkg/Library/BaseCpuLib/LoongArch/InitializeFpu.S
@@ -0,0 +1,51 @@
+#------------------------------------------------------------------------------
+#
+# InitializeFloatingPointUnits() for LoongArch64
+#
+# Copyright (c) 2023, Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#------------------------------------------------------------------------------
+ASM_GLOBAL ASM_PFX(InitializeFloatingPointUnits)
+
+ASM_PFX(InitializeFloatingPointUnits):
+  li.d        $t0, 0x0      // RNE mode
+  movgr2fcsr  $r0, $t0
+  li.d        $t1, -1       // SNaN
+
+  movgr2fr.d  $f0, $t1
+  movgr2fr.d  $f1, $t1
+  movgr2fr.d  $f2, $t1
+  movgr2fr.d  $f3, $t1
+  movgr2fr.d  $f4, $t1
+  movgr2fr.d  $f5, $t1
+  movgr2fr.d  $f6, $t1
+  movgr2fr.d  $f7, $t1
+  movgr2fr.d  $f8, $t1
+  movgr2fr.d  $f9, $t1
+  movgr2fr.d  $f10, $t1
+  movgr2fr.d  $f11, $t1
+  movgr2fr.d  $f12, $t1
+  movgr2fr.d  $f13, $t1
+  movgr2fr.d  $f14, $t1
+  movgr2fr.d  $f15, $t1
+  movgr2fr.d  $f16, $t1
+  movgr2fr.d  $f17, $t1
+  movgr2fr.d  $f18, $t1
+  movgr2fr.d  $f19, $t1
+  movgr2fr.d  $f20, $t1
+  movgr2fr.d  $f21, $t1
+  movgr2fr.d  $f22, $t1
+  movgr2fr.d  $f23, $t1
+  movgr2fr.d  $f24, $t1
+  movgr2fr.d  $f25, $t1
+  movgr2fr.d  $f26, $t1
+  movgr2fr.d  $f27, $t1
+  movgr2fr.d  $f28, $t1
+  movgr2fr.d  $f29, $t1
+  movgr2fr.d  $f30, $t1
+  movgr2fr.d  $f31, $t1
+
+  jirl $zero, $ra, 0
+  .end
-- 
2.27.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#110546): https://edk2.groups.io/g/devel/message/110546
Mute This Topic: https://groups.io/mt/102342356/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* [edk2-devel] [PATCH v1 03/29] MdePkg: Add LoongArch64 exception function set into BaseLib
       [not found] <20231102134249.3983594-1-lichao@loongson.cn>
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 02/29] MdePkg: Add LoongArch64 FPU function set into BaseCpuLib Chao Li
@ 2023-11-02 13:42 ` Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 05/29] MdePkg: Add LoongArch Cpucfg function Chao Li
                   ` (15 subsequent siblings)
  17 siblings, 0 replies; 18+ messages in thread
From: Chao Li @ 2023-11-02 13:42 UTC (permalink / raw)
  To: devel; +Cc: Michael D Kinney, Liming Gao, Zhiguang Liu

Adding SetExceptionBaseAddress and SetTlbRebaseAddress functions
for LoongArch64.

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

Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
Cc: Zhiguang Liu <zhiguang.liu@intel.com>
Signed-off-by: Chao Li <lichao@loongson.cn>
---
 MdePkg/Include/Library/BaseLib.h              | 20 +++++++++
 MdePkg/Library/BaseLib/BaseLib.inf            |  1 +
 .../BaseLib/LoongArch64/ExceptionBase.S       | 41 +++++++++++++++++++
 3 files changed, 62 insertions(+)
 create mode 100644 MdePkg/Library/BaseLib/LoongArch64/ExceptionBase.S

diff --git a/MdePkg/Include/Library/BaseLib.h b/MdePkg/Include/Library/BaseLib.h
index 5d7067ee85..a9a69c734c 100644
--- a/MdePkg/Include/Library/BaseLib.h
+++ b/MdePkg/Include/Library/BaseLib.h
@@ -229,6 +229,26 @@ typedef struct {
 
 #define BASE_LIBRARY_JUMP_BUFFER_ALIGNMENT  8
 
+/*
+ * Set the exception base address for LoongArch.
+ *
+ * @param  ExceptionBaseAddress   The exception base address, must be aligned greater than or qeual to 4K .
+ */
+VOID
+SetExceptionBaseAddress (
+  IN UINT64
+  );
+
+/*
+ * Set the TlbRebase address for LoongArch.
+ *
+ * @param  TlbRebaseAddress   The TlbRebase address, must be aligned greater than or qeual to 4K .
+ */
+VOID
+SetTlbRebaseAddress (
+  IN UINT64
+  );
+
 #endif // defined (MDE_CPU_LOONGARCH64)
 
 //
diff --git a/MdePkg/Library/BaseLib/BaseLib.inf b/MdePkg/Library/BaseLib/BaseLib.inf
index 03c7b02e82..a18fe5efb4 100644
--- a/MdePkg/Library/BaseLib/BaseLib.inf
+++ b/MdePkg/Library/BaseLib/BaseLib.inf
@@ -419,6 +419,7 @@
   LoongArch64/CpuPause.S            | GCC
   LoongArch64/SetJumpLongJump.S     | GCC
   LoongArch64/SwitchStack.S         | GCC
+  LoongArch64/ExceptionBase.S       | GCC
 
 [Packages]
   MdePkg/MdePkg.dec
diff --git a/MdePkg/Library/BaseLib/LoongArch64/ExceptionBase.S b/MdePkg/Library/BaseLib/LoongArch64/ExceptionBase.S
new file mode 100644
index 0000000000..36c6ca7ca8
--- /dev/null
+++ b/MdePkg/Library/BaseLib/LoongArch64/ExceptionBase.S
@@ -0,0 +1,41 @@
+#------------------------------------------------------------------------------
+#
+# LoongArch set exception base address operations
+#
+# Copyright (c) 2023, Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#------------------------------------------------------------------------------
+
+#include <Base.h>
+#include <Register/LoongArch64/Csr.h>
+
+ASM_GLOBAL ASM_PFX(SetExceptionBaseAddress)
+ASM_GLOBAL ASM_PFX(SetTlbRebaseAddress)
+
+#/**
+#  Set the exception base address for LoongArch.
+#
+#  @param  ExceptionBaseAddress   The exception base address, must be aligned greater than or qeual to 4K .
+#**/
+ASM_PFX(SetExceptionBaseAddress):
+  csrrd   $t0, LOONGARCH_CSR_ECFG
+  li.d    $t1, ~(BIT16 | BIT17 | BIT18)
+  and     $t0, $t0, $t1
+  csrwr   $t0, LOONGARCH_CSR_ECFG
+
+  move    $t0, $a0
+  csrwr   $t0, LOONGARCH_CSR_EBASE
+  jirl    $zero, $ra, 0
+
+#/**
+#  Set the TlbRebase address for LoongArch.
+#
+#  @param  TlbRebaseAddress   The TlbRebase address, must be aligned greater than or qeual to 4K .
+#**/
+ASM_PFX(SetTlbRebaseAddress):
+  move    $t0, $a0
+  csrwr   $t0, LOONGARCH_CSR_TLBREBASE
+  jirl    $zero, $ra, 0
+.end
-- 
2.27.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#110534): https://edk2.groups.io/g/devel/message/110534
Mute This Topic: https://groups.io/mt/102342189/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* [edk2-devel] [PATCH v1 05/29] MdePkg: Add LoongArch Cpucfg function
       [not found] <20231102134249.3983594-1-lichao@loongson.cn>
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 02/29] MdePkg: Add LoongArch64 FPU function set into BaseCpuLib Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 03/29] MdePkg: Add LoongArch64 exception function set into BaseLib Chao Li
@ 2023-11-02 13:42 ` Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 06/29] MdePkg: Add read stable counter operation for LoongArch Chao Li
                   ` (14 subsequent siblings)
  17 siblings, 0 replies; 18+ messages in thread
From: Chao Li @ 2023-11-02 13:42 UTC (permalink / raw)
  To: devel; +Cc: Michael D Kinney, Liming Gao, Zhiguang Liu

Add LoongArch AsmCpucfg function and Cpucfg definitions.

Also added Include/Register/LoongArch64/Cpucfg.h to IgnoreFiles of
EccCheck.

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

Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
Cc: Zhiguang Liu <zhiguang.liu@intel.com>
Signed-off-by: Chao Li <lichao@loongson.cn>
---
 MdePkg/Include/Library/BaseLib.h             |  12 +
 MdePkg/Include/Register/LoongArch64/Cpucfg.h | 565 +++++++++++++++++++
 MdePkg/Library/BaseLib/BaseLib.inf           |   1 +
 MdePkg/Library/BaseLib/LoongArch64/Cpucfg.S  |  26 +
 MdePkg/MdePkg.ci.yaml                        |   3 +-
 5 files changed, 606 insertions(+), 1 deletion(-)
 create mode 100644 MdePkg/Include/Register/LoongArch64/Cpucfg.h
 create mode 100644 MdePkg/Library/BaseLib/LoongArch64/Cpucfg.S

diff --git a/MdePkg/Include/Library/BaseLib.h b/MdePkg/Include/Library/BaseLib.h
index 93a014cd49..3adf4d0042 100644
--- a/MdePkg/Include/Library/BaseLib.h
+++ b/MdePkg/Include/Library/BaseLib.h
@@ -269,6 +269,18 @@ DisableLocalInterrupts (
   IN UINT16
   );
 
+/**
+  Read CPUCFG register.
+
+  @param  Index  Specifies the register number of the CPUCFG to read the data.
+  @param  Data   A pointer to the variable used to store the CPUCFG register value.
+**/
+VOID
+AsmCpucfg (
+  IN  UINT32  Index,
+  OUT UINT32  *Data
+  );
+
 #endif // defined (MDE_CPU_LOONGARCH64)
 
 //
diff --git a/MdePkg/Include/Register/LoongArch64/Cpucfg.h b/MdePkg/Include/Register/LoongArch64/Cpucfg.h
new file mode 100644
index 0000000000..841885dc70
--- /dev/null
+++ b/MdePkg/Include/Register/LoongArch64/Cpucfg.h
@@ -0,0 +1,565 @@
+/** @file
+  CPUCFG definitions.
+
+  Copyright (c) 2023, Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#ifndef CPUCFG_H_
+#define CPUCFG_H_
+
+/**
+  CPUCFG REG0 Information
+
+  @code
+  CPUCFG_REG0_INFO_DATA
+ **/
+#define CPUCFG_REG0_INFO  0x0
+
+/**
+  CPUCFG REG0 Information returned data.
+  #CPUCFG_REG0_INFO
+ **/
+typedef union {
+  struct {
+    ///
+    /// [Bit 31:0] Processor Identity.
+    ///
+    UINT32    PRID : 32;
+  } Bits;
+  ///
+  /// All bit fields as a 32-bit value
+  ///
+  UINT32    Uint32;
+} CPUCFG_REG0_INFO_DATA;
+
+/**
+  CPUCFG REG1 Information
+
+  @code
+  CPUCFG_REG1_INFO_DATA
+ **/
+#define CPUCFG_REG1_INFO  0x1
+
+/**
+  CPUCFG REG1 Information returned data.
+  #CPUCFG_REG1_INFO
+ **/
+typedef union {
+  struct {
+    ///
+    /// [Bit 1:0] Architecture:
+    ///           2'b00 indicates the implementation of simplified LoongAarch32;
+    ///           2'b01 indicates the implementation of LoongAarch32;
+    ///           2'b10 indicates the implementation of LoongAarch64;
+    ///           2'b11 reserved;
+    ///
+    UINT32    ARCH      : 2;
+    ///
+    /// [Bit 2] Paging mapping mode. A value of 1 indicates the processor MMU supports
+    /// page mapping mode.
+    ///
+    UINT32    PGMMU     : 1;
+    ///
+    /// [Bit 3] A value of 1 indicates the processor supports the IOCSR instruction.
+    ///
+    UINT32    IOCSR     : 1;
+    ///
+    /// [Bit 11:4] Physical address bits. The supported physical address bits PALEN value
+    /// minus 1.
+    ///
+    UINT32    PALEN     : 8;
+    ///
+    /// [Bit 19:12] Virtual address bits. The supported virtual address bits VALEN value
+    /// minus 1.
+    ///
+    UINT32    VALEN     : 8;
+    ///
+    /// [Bit 20] Non-aligned Memory Access. A value of 1 indicates the processor supports
+    /// non-aligned memory access.
+    ///
+    UINT32    UAL       : 1;
+    ///
+    /// [Bit 21] Page Read Inhibit. A value of 1 indicates the processor supports page
+    /// attribute of "Read Inhibit".
+    ///
+    UINT32    RI        : 1;
+    ///
+    /// [Bit 22] Page Execution Protection. A value of 1 indicates the processor supports
+    /// page attribute of "Execution Protection".
+    ///
+    UINT32    EP        : 1;
+    ///
+    /// [Bit 23] A value of 1 indicates the processor supports for page attributes of RPLV.
+    ///
+    UINT32    RPLV      : 1;
+    ///
+    /// [Bit 24] Huge Page. A value of 1 indicates the processor supports page attribute
+    /// of huge page.
+    ///
+    UINT32    HP        : 1;
+    ///
+    /// [Bit 25] A value of 1 indicates that the string of processor product information
+    /// is recorded at address 0 of the IOCSR access space.
+    ///
+    UINT32    IOCSR_BRD : 1;
+    ///
+    /// [Bit 26] A value of 1 indicates that the external interrupt uses the message
+    /// interrupt mode, otherwise it is the level interrupt line mode.
+    ///
+    UINT32    MSG_INT   : 1;
+    ///
+    /// [Bit 31:27] Reserved.
+    ///
+    UINT32    Reserved  : 5;
+  } Bits;
+  ///
+  /// All bit fields as a 32-bit value
+  ///
+  UINT32    Uint32;
+} CPUCFG_REG1_INFO_DATA;
+
+/**
+  CPUCFG REG2 Information
+
+  @code
+  CPUCFG_REG2_INFO_DATA
+ **/
+#define CPUCFG_REG2_INFO  0x2
+
+/**
+  CPUCFG REG2 Information returned data.
+  #CPUCFG_REG2_INFO
+ **/
+typedef union {
+  struct {
+    ///
+    /// [Bit 0] Basic Floating-Point. A value of 1 indicates the processor supports basic
+    /// floating-point instructions.
+    ///
+    UINT32    FP       : 1;
+    ///
+    /// [Bit 1] Sigle-Precision. A value of 1 indicates the processor supports sigle-precision
+    /// floating-point numbers.
+    ///
+    UINT32    FP_SP    : 1;
+    ///
+    /// [Bit 2] Double-Precision. A value of 1 indicates the processor supports double-precision
+    /// floating-point numbers.
+    ///
+    UINT32    FP_DP    : 1;
+    ///
+    /// [Bit 5:3] The version number of the floating-point arithmetic standard. 1 is the initial
+    /// version number, indicating that it is compatible with the IEEE 754-2008 standard.
+    ///
+    UINT32    FP_ver   : 3;
+    ///
+    /// [Bit 6] 128-bit Vector Extension. A value of 1 indicates the processor supports 128-bit
+    /// vector extension.
+    ///
+    UINT32    LSX      : 1;
+    ///
+    /// [Bit 7] 256-bit Vector Extension. A value of 1 indicates the processor supports 256-bit
+    /// vector extension.
+    ///
+    UINT32    LASX     : 1;
+    ///
+    /// [Bit 8] Complex Vector Operation Instructions. A value of 1 indicates the processor supports
+    /// complex vector operation instructions.
+    ///
+    UINT32    COMPLEX  : 1;
+    ///
+    /// [Bit 9] Encryption And Decryption Vector Instructions. A value of 1 indicates the processor
+    /// supports encryption and decryption vector instructions.
+    ///
+    UINT32    CRYPTO   : 1;
+    ///
+    /// [Bit 10] Virtualization Expansion. A value of 1 indicates the processor supports
+    /// virtualization expansion.
+    ///
+    UINT32    LVZ      : 1;
+    ///
+    /// [Bit 13:11] The version number of the virtualization hardware acceleration specification.
+    /// 1 is the initial version number.
+    ///
+    UINT32    LVZ_ver  : 3;
+    ///
+    /// [Bit 14] Constant Frequency Counter And Timer. A value of 1 indicates the processor supports
+    /// constant frequency counter and timer.
+    ///
+    UINT32    LLFTP    : 1;
+    ///
+    /// [Bit 17:15] Constant frequency counter and timer version number. 1 is the initial version.
+    ///
+    UINT32    LLTP_ver : 3;
+    ///
+    /// [Bit 18] X86 Binary Translation Extension. A value of 1 indicates the processor supports
+    /// X86 binary translation extension.
+    ///
+    UINT32    LBT_X86  : 1;
+    ///
+    /// [Bit 19] ARM Binary Translation Extension. A value of 1 indicates the processor supports
+    /// ARM binary translation extension.
+    ///
+    UINT32    LBT_ARM  : 1;
+    ///
+    /// [Bit 20] MIPS Binary Translation Extension. A value of 1 indicates the processor supports
+    /// MIPS binary translation extension.
+    ///
+    UINT32    LBT_MIPS : 1;
+    ///
+    /// [Bit 21] Software Page Table Walking Instruction. A value of 1 indicates the processor
+    /// supports software page table walking instruction.
+    ///
+    UINT32    LSPW     : 1;
+    ///
+    /// [Bit 22] Atomic Memory Access Instruction. A value of 1 indicates the processor supports
+    /// AM* atomic memory access instruction.
+    ///
+    UINT32    LAM      : 1;
+    ///
+    /// [Bit 31:23] Reserved.
+    ///
+    UINT32    Reserved : 9;
+  } Bits;
+  ///
+  /// All bit fields as a 32-bit value
+  ///
+  UINT32    Uint32;
+} CPUCFG_REG2_INFO_DATA;
+
+/**
+  CPUCFG REG3 Information
+
+  @code
+  CPUCFG_REG3_INFO_DATA
+ **/
+#define CPUCFG_REG3_INFO  0x3
+
+/**
+  CPUCFG REG3 Information returned data.
+  #CPUCFG_REG3_INFO
+ **/
+typedef union {
+  struct {
+    ///
+    /// [Bit 0] Hardware Cache Coherent DMA. A value of 1 indicates the processor supports
+    /// hardware cache coherent DMA.
+    ///
+    UINT32    CCDMA     : 1;
+    ///
+    /// [Bit 1] Store Fill Buffer. A value of 1 indicates the processor supports store fill
+    /// buffer (SFB).
+    ///
+    UINT32    SFB       : 1;
+    ///
+    /// [Bit 2] Uncache Accelerate. A value of 1 indicates the processor supports uncache
+    /// accelerate.
+    ///
+    UINT32    UCACC     : 1;
+    ///
+    /// [Bit 3] A value of 1 indicates the processor supports LL instruction to fetch exclusive
+    /// block function.
+    ///
+    UINT32    LLEXC     : 1;
+    ///
+    /// [Bit 4] A value of 1 indicates the processor supports random delay function after SC
+    /// instruction.
+    ///
+    UINT32    SCDLY     : 1;
+    ///
+    /// [Bit 5] A value of 1 indicates the processor supports LL automatic with dbar function.
+    ///
+    UINT32    LLDBAR    : 1;
+    ///
+    /// [Bit 6] A value of 1 indicates the processor supports the hardware maintains the
+    /// consistency between ITLB and TLB.
+    ///
+    UINT32    ITLBT     : 1;
+    ///
+    /// [Bit 7] A value of 1 indicates the processor supports the hardware maintains the data
+    /// consistency between ICache and DCache in one processor core.
+    ///
+    UINT32    ICACHET   : 1;
+    ///
+    /// [Bit 10:8] The maximum number of directory levels supported by the page walk instruction.
+    ///
+    UINT32    SPW_LVL   : 3;
+    ///
+    /// [Bit 11] A value of 1 indicates the processor supports the page walk instruction fills
+    /// the TLB in half when it encounters a large page.
+    ///
+    UINT32    SPW_HP_HF : 1;
+    ///
+    /// [Bit 12] Virtual Address Range. A value of 1 indicates the processor supports the software
+    /// configuration can be used to shorten the virtual address range.
+    ///
+    UINT32    RVA       : 1;
+    ///
+    /// [Bit 16:13] The maximum configurable virtual address is shortened by -1.
+    ///
+    UINT32    RVAMAX_1  : 4;
+    ///
+    /// [Bit 31:17] Reserved.
+    ///
+    UINT32    Reserved  : 15;
+  } Bits;
+  ///
+  /// All bit fields as a 32-bit value
+  ///
+  UINT32    Uint32;
+} CPUCFG_REG3_INFO_DATA;
+
+/**
+  CPUCFG REG4 Information
+
+  @code
+  CPUCFG_REG4_INFO_DATA
+ **/
+#define CPUCFG_REG4_INFO  0x4
+
+/**
+  CPUCFG REG4 Information returned data.
+  #CPUCFG_REG4_INFO
+ **/
+typedef union {
+  struct {
+    ///
+    /// [Bit 31:0] Constant frequency timer and the crystal frequency corresponding to the clock
+    /// used by the timer.
+    ///
+    UINT32    CC_FREQ : 32;
+  } Bits;
+  ///
+  /// All bit fields as a 32-bit value
+  ///
+  UINT32    Uint32;
+} CPUCFG_REG4_INFO_DATA;
+
+/**
+  CPUCFG REG5 Information
+
+  @code
+  CPUCFG_REG5_INFO_DATA
+ **/
+#define CPUCFG_REG5_INFO  0x5
+
+/**
+  CPUCFG REG5 Information returned data.
+  #CPUCFG_REG5_INFO
+ **/
+typedef union {
+  struct {
+    ///
+    /// [Bit 15:0] Constant frequency timer and the corresponding multiplication factor of the
+    /// clock used by the timer.
+    ///
+    UINT32    CC_MUL : 16;
+    ///
+    /// [Bit 31:16] Constant frequency timer and the division coefficient corresponding to the
+    /// clock used by the timer
+    ///
+    UINT32    CC_DIV : 16;
+  } Bits;
+  ///
+  /// All bit fields as a 32-bit value
+  ///
+  UINT32    Uint32;
+} CPUCFG_REG5_INFO_DATA;
+
+/**
+  CPUCFG REG6 Information
+
+  @code
+  CPUCFG_REG6_INFO_DATA
+ **/
+#define CPUCFG_REG6_INFO  0x6
+
+/**
+  CPUCFG REG6 Information returned data.
+  #CPUCFG_REG6_INFO
+ **/
+typedef union {
+  struct {
+    ///
+    /// [Bit 0] Performance Counter. A value of 1 indicates the processor supports performance
+    /// counter.
+    ///
+    UINT32    PMP      : 1;
+    ///
+    /// [Bit 3:1] In the performance monitor, the architecture defines the version number of the
+    /// event, and 1 is the initial version
+    ///
+    UINT32    PMVER    : 3;
+    ///
+    /// [Bit 7:4] Number of performance monitors minus 1.
+    ///
+    UINT32    PMNUM    : 4;
+    ///
+    /// [Bit 13:8] Number of bits of a performance monitor minus 1.
+    ///
+    UINT32    PMBITS   : 6;
+    ///
+    /// [Bit 14] A value of 1 indicates the processor supports reading performance counter in user mode.
+    ///
+    UINT32    UPM      : 1;
+    ///
+    /// [Bit 31:15] Reserved.
+    ///
+    UINT32    Reserved : 17;
+  } Bits;
+  ///
+  /// All bit fields as a 32-bit value
+  ///
+  UINT32    Uint32;
+} CPUCFG_REG6_INFO_DATA;
+
+/**
+  CPUCFG REG16 Information
+
+  @code
+  CPUCFG_REG16_INFO_DATA
+ **/
+#define CPUCFG_REG16_INFO  0x10
+
+/**
+  CPUCFG REG16 Information returned data.
+  #CPUCFG_REG16_INFO
+ **/
+typedef union {
+  struct {
+    ///
+    /// [Bit 0] A value of 1 indicates the processor has a first-level instruction cache
+    /// or a first-level unified cache
+    ///
+    UINT32    L1_IU_Present   : 1;
+    ///
+    /// [Bit 1] A value of 1 indicates that the cache shown by L1 IU_Present is the
+    /// unified cache.
+    ///
+    UINT32    L1_IU_Unify     : 1;
+    ///
+    /// [Bit 2] A value of 1 indicates the processor has a first-level data cache.
+    ///
+    UINT32    L1_D_Present    : 1;
+    ///
+    /// [Bit 3] A value of 1 indicates the processor has a second-level instruction cache
+    /// or a second-level unified cache.
+    ///
+    UINT32    L2_IU_Present   : 1;
+    ///
+    /// [Bit 4] A value of 1 indicates that the cache shown by L2 IU_Present is the
+    /// unified cache.
+    ///
+    UINT32    L2_IU_Unify     : 1;
+    ///
+    /// [Bit 5] A value of 1 indicates that the cache shown by L2 IU_Present is private
+    /// to each core.
+    ///
+    UINT32    L2_IU_Private   : 1;
+    ///
+    /// [Bit 6] A value of 1 indicates that the cache shown by L2 IU_Present has an inclusive
+    /// relationship to the lower levels (L1).
+    ///
+    UINT32    L2_IU_Inclusive : 1;
+    ///
+    /// [Bit 7] A value of 1 indicates the processor has a second-level data cache.
+    ///
+    UINT32    L2_D_Present    : 1;
+    ///
+    /// [Bit 8] A value of 1 indicates that the second-level data cache is private to each core.
+    ///
+    UINT32    L2_D_Private    : 1;
+    ///
+    /// [Bit 9] A value of 1 indicates that the second-level data cache has a containment
+    /// relationship to the lower level (L1).
+    ///
+    UINT32    L2_D_Inclusive  : 1;
+    ///
+    /// [Bit 10] A value of 1 indicates the processor has a three-level instruction cache
+    /// or a second-level unified Cache.
+    ///
+    UINT32    L3_IU_Present   : 1;
+    ///
+    /// [Bit 11] A value of 1 indicates that the cache shown by L3 IU_Present is the
+    /// unified cache.
+    ///
+    UINT32    L3_IU_Unify     : 1;
+    ///
+    /// [Bit 12] A value of 1 indicates that the cache shown by L3 IU_Present is private
+    /// to each core.
+    ///
+    UINT32    L3_IU_Private   : 1;
+    ///
+    /// [Bit 13] A value of 1 indicates that the cache shown by L3 IU_Present has an inclusive
+    /// relationship to the lower levels (L1 and L2).
+    ///
+    UINT32    L3_IU_Inclusive : 1;
+    ///
+    /// [Bit 14] A value of 1 indicates the processor has a three-level data cache.
+    ///
+    UINT32    L3_D_Present    : 1;
+    ///
+    /// [Bit 15] A value of 1 indicates that the three-level data cache is private to each core.
+    ///
+    UINT32    L3_D_Private    : 1;
+    ///
+    /// [Bit 16] A value of 1 indicates that the three-level data cache has a containment
+    /// relationship to the lower level (L1 and L2).
+    ///
+    UINT32    L3_D_Inclusive  : 1;
+    ///
+    /// [Bit 31:17] Reserved.
+    ///
+    UINT32    Reserved        : 15;
+  } Bits;
+  ///
+  /// All bit fields as a 32-bit value
+  ///
+  UINT32    Uint32;
+} CPUCFG_REG16_INFO_DATA;
+
+/**
+  CPUCFG REG17, REG18, REG19 and REG20 Information
+
+  @code
+  CPUCFG_CACHE_INFO_DATA
+ **/
+#define CPUCFG_REG17_INFO  0x11 /// L1 unified cache.
+#define CPUCFG_REG18_INFO  0x12 /// L1 data cache.
+#define CPUCFG_REG19_INFO  0x13 /// L2 unified cache.
+#define CPUCFG_REG20_INFO  0x14 /// L3 unified cache.
+
+/**
+  CPUCFG CACHE Information returned data.
+  #CPUCFG_REG17_INFO
+  #CPUCFG_REG18_INFO
+  #CPUCFG_REG19_INFO
+  #CPUCFG_REG20_INFO
+ **/
+typedef union {
+  struct {
+    ///
+    /// [Bit 15:0] Number of channels minus 1.
+    ///
+    UINT32    Way_1         : 16;
+    ///
+    /// [Bit 23:16] Log2 (number of cache rows per channel).
+    ///
+    UINT32    Index_log2    : 8;
+    ///
+    /// [Bit 30:24] Log2 (cache row bytes).
+    ///
+    UINT32    Linesize_log2 : 7;
+    ///
+    /// [Bit 31] Reserved.
+    ///
+    UINT32    Reserved      : 1;
+  } Bits;
+  ///
+  /// All bit fields as a 32-bit value
+  ///
+  UINT32    Uint32;
+} CPUCFG_CACHE_INFO_DATA;
+#endif
diff --git a/MdePkg/Library/BaseLib/BaseLib.inf b/MdePkg/Library/BaseLib/BaseLib.inf
index a18fe5efb4..a427aa9359 100644
--- a/MdePkg/Library/BaseLib/BaseLib.inf
+++ b/MdePkg/Library/BaseLib/BaseLib.inf
@@ -420,6 +420,7 @@
   LoongArch64/SetJumpLongJump.S     | GCC
   LoongArch64/SwitchStack.S         | GCC
   LoongArch64/ExceptionBase.S       | GCC
+  LoongArch64/Cpucfg.S              | GCC
 
 [Packages]
   MdePkg/MdePkg.dec
diff --git a/MdePkg/Library/BaseLib/LoongArch64/Cpucfg.S b/MdePkg/Library/BaseLib/LoongArch64/Cpucfg.S
new file mode 100644
index 0000000000..7ed49146b4
--- /dev/null
+++ b/MdePkg/Library/BaseLib/LoongArch64/Cpucfg.S
@@ -0,0 +1,26 @@
+#------------------------------------------------------------------------------
+#
+# AsmCpucfg for LoongArch
+#
+# Copyright (c) 2023, Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#------------------------------------------------------------------------------
+
+ASM_GLOBAL ASM_PFX(AsmCpucfg)
+
+#/**
+#  Read CPUCFG register.
+#
+#  @param   a0 Specifies the register number of the CPUCFG to read the data.
+#  @param   a1 Pointer to the variable used to store the CPUCFG register value.
+#
+#**/
+
+ASM_PFX(AsmCpucfg):
+  cpucfg  $t0, $a0
+  stptr.d $t0, $a1, 0
+
+  jirl    $zero, $ra, 0
+  .end
diff --git a/MdePkg/MdePkg.ci.yaml b/MdePkg/MdePkg.ci.yaml
index 1d3d8327b1..f2d81af080 100644
--- a/MdePkg/MdePkg.ci.yaml
+++ b/MdePkg/MdePkg.ci.yaml
@@ -80,7 +80,8 @@
             "Include/Register/Amd/SmramSaveStateMap.h",
             "Test/UnitTest/Library/DevicePathLib/TestDevicePathLib.c",
             "Test/UnitTest/Library/DevicePathLib/TestDevicePathLib.h",
-            "Test/UnitTest/Library/DevicePathLib/TestDevicePathStringConversions.c"
+            "Test/UnitTest/Library/DevicePathLib/TestDevicePathStringConversions.c",
+            "Include/Register/LoongArch64/Cpucfg.h"
         ]
     },
     ## options defined ci/Plugin/CompilerPlugin
-- 
2.27.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#110537): https://edk2.groups.io/g/devel/message/110537
Mute This Topic: https://groups.io/mt/102342238/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* [edk2-devel] [PATCH v1 06/29] MdePkg: Add read stable counter operation for LoongArch
       [not found] <20231102134249.3983594-1-lichao@loongson.cn>
                   ` (2 preceding siblings ...)
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 05/29] MdePkg: Add LoongArch Cpucfg function Chao Li
@ 2023-11-02 13:42 ` Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 08/29] MdePkg: Add IOCSR " Chao Li
                   ` (13 subsequent siblings)
  17 siblings, 0 replies; 18+ messages in thread
From: Chao Li @ 2023-11-02 13:42 UTC (permalink / raw)
  To: devel; +Cc: Michael D Kinney, Liming Gao, Zhiguang Liu

Add LoongArch gets stable counter ASM function.

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

Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
Cc: Zhiguang Liu <zhiguang.liu@intel.com>
Signed-off-by: Chao Li <lichao@loongson.cn>
---
 MdePkg/Include/Library/BaseLib.h              | 12 ++++++++++
 MdePkg/Library/BaseLib/BaseLib.inf            |  1 +
 .../BaseLib/LoongArch64/ReadStableCounter.S   | 24 +++++++++++++++++++
 3 files changed, 37 insertions(+)
 create mode 100644 MdePkg/Library/BaseLib/LoongArch64/ReadStableCounter.S

diff --git a/MdePkg/Include/Library/BaseLib.h b/MdePkg/Include/Library/BaseLib.h
index 3adf4d0042..55d53c75a0 100644
--- a/MdePkg/Include/Library/BaseLib.h
+++ b/MdePkg/Include/Library/BaseLib.h
@@ -281,6 +281,18 @@ AsmCpucfg (
   OUT UINT32  *Data
   );
 
+/**
+  Gets the timer count value.
+
+  @param[] VOID
+  @retval  timer count value.
+
+**/
+UINTN
+AsmReadStableCounter (
+  VOID
+  );
+
 #endif // defined (MDE_CPU_LOONGARCH64)
 
 //
diff --git a/MdePkg/Library/BaseLib/BaseLib.inf b/MdePkg/Library/BaseLib/BaseLib.inf
index a427aa9359..aaf221822b 100644
--- a/MdePkg/Library/BaseLib/BaseLib.inf
+++ b/MdePkg/Library/BaseLib/BaseLib.inf
@@ -421,6 +421,7 @@
   LoongArch64/SwitchStack.S         | GCC
   LoongArch64/ExceptionBase.S       | GCC
   LoongArch64/Cpucfg.S              | GCC
+  LoongArch64/ReadStableCounter.S   | GCC
 
 [Packages]
   MdePkg/MdePkg.dec
diff --git a/MdePkg/Library/BaseLib/LoongArch64/ReadStableCounter.S b/MdePkg/Library/BaseLib/LoongArch64/ReadStableCounter.S
new file mode 100644
index 0000000000..59c877211d
--- /dev/null
+++ b/MdePkg/Library/BaseLib/LoongArch64/ReadStableCounter.S
@@ -0,0 +1,24 @@
+#------------------------------------------------------------------------------
+#
+# LoongArch Read Stable Counter
+#
+# Copyright (c) 2023, Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#------------------------------------------------------------------------------
+
+ASM_GLOBAL ASM_PFX(AsmReadStableCounter)
+
+#/**
+#  Gets the timer count value.
+#
+#  @param[] VOID
+#  @retval  timer count value.
+#
+#**/
+
+ASM_PFX(AsmReadStableCounter):
+  rdtime.d   $a0, $zero
+  jirl       $zero, $ra, 0
+  .end
-- 
2.27.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#110528): https://edk2.groups.io/g/devel/message/110528
Mute This Topic: https://groups.io/mt/102342165/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* [edk2-devel] [PATCH v1 08/29] MdePkg: Add IOCSR operation for LoongArch
       [not found] <20231102134249.3983594-1-lichao@loongson.cn>
                   ` (3 preceding siblings ...)
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 06/29] MdePkg: Add read stable counter operation for LoongArch Chao Li
@ 2023-11-02 13:42 ` Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 09/29] UefiCpuPkg: Add LoongArch64 CPU Timer library Chao Li
                   ` (12 subsequent siblings)
  17 siblings, 0 replies; 18+ messages in thread
From: Chao Li @ 2023-11-02 13:42 UTC (permalink / raw)
  To: devel; +Cc: Michael D Kinney, Liming Gao, Zhiguang Liu

Add IoCsrRead8, IoCsrRead16, IoCsrRead32, IoCsrRead64, IoCsrWrite8,
IoCsrWrite16, IoCsrWrite32, IoCsrWrite64 to operate the IOCSR registers
of LoongArch architecture.

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

Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
Cc: Zhiguang Liu <zhiguang.liu@intel.com>
Signed-off-by: Chao Li <lichao@loongson.cn>
---
 MdePkg/Include/Library/BaseLib.h           | 112 +++++++++++++++++++
 MdePkg/Library/BaseLib/BaseLib.inf         |   1 +
 MdePkg/Library/BaseLib/LoongArch64/IoCsr.S | 120 +++++++++++++++++++++
 3 files changed, 233 insertions(+)
 create mode 100644 MdePkg/Library/BaseLib/LoongArch64/IoCsr.S

diff --git a/MdePkg/Include/Library/BaseLib.h b/MdePkg/Include/Library/BaseLib.h
index 234f3065c2..88ee6e9d51 100644
--- a/MdePkg/Include/Library/BaseLib.h
+++ b/MdePkg/Include/Library/BaseLib.h
@@ -338,6 +338,118 @@ CsrXChg (
   IN UINTN   Mask
   );
 
+/**
+  IO CSR read byte operation.
+
+  @param[in]  Select   IO CSR read instruction select values.
+
+  @return     The return value of iocsrrd.b instruction.
+
+**/
+UINT8
+IoCsrRead8 (
+  IN UINTN  Select
+  );
+
+/**
+  IO CSR read half word operation.
+
+  @param[in]  Select   IO CSR read instruction select values.
+
+  @return     The return value of iocsrrd.h instruction.
+
+**/
+UINT16
+IoCsrRead16 (
+  IN UINTN  Select
+  );
+
+/**
+  IO CSR read word operation.
+
+  @param[in]  Select   IO CSR read instruction select values.
+
+  @return     The return value of iocsrrd.w instruction.
+
+**/
+UINT32
+IoCsrRead32 (
+  IN UINTN  Select
+  );
+
+/**
+  IO CSR read double word operation. Only for LoongArch64.
+
+  @param[in]  Select   IO CSR read instruction select values.
+
+  @return     The return value of iocsrrd.d instruction.
+
+**/
+UINT64
+IoCsrRead64 (
+  IN UINTN  Select
+  );
+
+/**
+  IO CSR write byte operation.
+
+  @param[in]  Select   IO CSR write instruction select values.
+  @param[in]  Value    The iocsrwr.b will write the value.
+
+  @return     VOID.
+
+**/
+VOID
+IoCsrWrite8 (
+  IN UINTN  Select,
+  IN UINT8  Value
+  );
+
+/**
+  IO CSR write half word operation.
+
+  @param[in]  Select   IO CSR write instruction select values.
+  @param[in]  Value    The iocsrwr.h will write the value.
+
+  @return     VOID.
+
+**/
+VOID
+IoCsrWrite16 (
+  IN UINTN   Select,
+  IN UINT16  Value
+  );
+
+/**
+  IO CSR write word operation.
+
+  @param[in]  Select   IO CSR write instruction select values.
+  @param[in]  Value    The iocsrwr.w will write the value.
+
+  @return     VOID.
+
+**/
+VOID
+IoCsrWrite32 (
+  IN UINTN   Select,
+  IN UINT32  Value
+  );
+
+/**
+  IO CSR write double word operation. Only for LoongArch64.
+
+  @param[in]  Select   IO CSR write instruction select values.
+  @param[in]  Value    The iocsrwr.d will write the value.
+
+  @return     VOID.
+
+**/
+VOID
+IoCsrWrite64 (
+  IN UINTN   Select,
+  IN UINT64  Value
+  );
+
 #endif // defined (MDE_CPU_LOONGARCH64)
 
 //
diff --git a/MdePkg/Library/BaseLib/BaseLib.inf b/MdePkg/Library/BaseLib/BaseLib.inf
index 74a323c798..e72724c1c1 100644
--- a/MdePkg/Library/BaseLib/BaseLib.inf
+++ b/MdePkg/Library/BaseLib/BaseLib.inf
@@ -412,6 +412,7 @@
   LoongArch64/Csr.c
   LoongArch64/InternalSwitchStack.c
   LoongArch64/AsmCsr.S              | GCC
+  LoongArch64/IoCsr.S               | GCC
   LoongArch64/GetInterruptState.S   | GCC
   LoongArch64/EnableInterrupts.S    | GCC
   LoongArch64/DisableInterrupts.S   | GCC
diff --git a/MdePkg/Library/BaseLib/LoongArch64/IoCsr.S b/MdePkg/Library/BaseLib/LoongArch64/IoCsr.S
new file mode 100644
index 0000000000..4c0009b93a
--- /dev/null
+++ b/MdePkg/Library/BaseLib/LoongArch64/IoCsr.S
@@ -0,0 +1,120 @@
+#------------------------------------------------------------------------------
+#
+# LoongArch ASM IO CSR operation functions
+#
+# Copyright (c) 2023, Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#------------------------------------------------------------------------------
+
+ASM_GLOBAL ASM_PFX (IoCsrRead8)
+ASM_GLOBAL ASM_PFX (IoCsrRead16)
+ASM_GLOBAL ASM_PFX (IoCsrRead32)
+ASM_GLOBAL ASM_PFX (IoCsrRead64)
+
+ASM_GLOBAL ASM_PFX (IoCsrWrite8)
+ASM_GLOBAL ASM_PFX (IoCsrWrite16)
+ASM_GLOBAL ASM_PFX (IoCsrWrite32)
+ASM_GLOBAL ASM_PFX (IoCsrWrite64)
+
+#/**
+#  IO CSR read byte operation.
+#
+#  @param[in]  Select   IO CSR read instruction select values.
+#
+#  @return     The return value of iocsrrd.b instruction.
+#
+#**/
+ASM_PFX (IoCsrRead8):
+  iocsrrd.b   $a0, $a0
+  jirl        $zero, $ra, 0
+
+#/**
+#  IO CSR read half word operation.
+#
+#  @param[in]  Select   IO CSR read instruction select values.
+#
+#  @return     The return value of iocsrrd.h instruction.
+#
+#**/
+ASM_PFX (IoCsrRead16):
+  iocsrrd.h   $a0, $a0
+  jirl        $zero, $ra, 0
+
+#/**
+#  IO CSR read word operation.
+#
+#  @param[in]  Select   IO CSR read instruction select values.
+#
+#  @return     The return value of iocsrrd.w instruction.
+#
+#**/
+ASM_PFX (IoCsrRead32):
+  iocsrrd.w   $a0, $a0
+  jirl        $zero, $ra, 0
+
+#/**
+#  IO CSR read double word operation. Only for LoongArch64.
+#
+#  @param[in]  Select   IO CSR read instruction select values.
+#
+#  @return     The return value of iocsrrd.d instruction.
+#
+#**/
+ASM_PFX (IoCsrRead64):
+  iocsrrd.d   $a0, $a0
+  jirl        $zero, $ra, 0
+
+#/**
+#  IO CSR write byte operation.
+#
+#  @param[in]  Select   IO CSR write instruction select values.
+#  @param[in]  Value    The iocsrwr.b will write the value.
+#
+#  @return     VOID.
+#
+#**/
+ASM_PFX (IoCsrWrite8):
+  iocsrwr.b   $a1, $a0
+  jirl        $zero, $ra, 0
+
+#/**
+#  IO CSR write half word operation.
+#
+#  @param[in]  Select   IO CSR write instruction select values.
+#  @param[in]  Value    The iocsrwr.h will write the value.
+#
+#  @return     VOID.
+#
+#**/
+ASM_PFX (IoCsrWrite16):
+  iocsrwr.h   $a1, $a0
+  jirl        $zero, $ra, 0
+
+#/**
+#  IO CSR write word operation.
+#
+#  @param[in]  Select   IO CSR write instruction select values.
+#  @param[in]  Value    The iocsrwr.w will write the value.
+#
+#  @return     VOID.
+#
+#**/
+ASM_PFX (IoCsrWrite32):
+  iocsrwr.w   $a1, $a0
+  jirl        $zero, $ra, 0
+
+#/**
+#  IO CSR write double word operation. Only for LoongArch64.
+#
+#  @param[in]  Select   IO CSR write instruction select values.
+#  @param[in]  Value    The iocsrwr.d will write the value.
+#
+#  @return     VOID.
+#
+#**/
+ASM_PFX (IoCsrWrite64):
+  iocsrwr.d   $a1, $a0
+  jirl        $zero, $ra, 0
+  .end
-- 
2.27.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#110539): https://edk2.groups.io/g/devel/message/110539
Mute This Topic: https://groups.io/mt/102342270/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* [edk2-devel] [PATCH v1 09/29] UefiCpuPkg: Add LoongArch64 CPU Timer library
       [not found] <20231102134249.3983594-1-lichao@loongson.cn>
                   ` (4 preceding siblings ...)
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 08/29] MdePkg: Add IOCSR " Chao Li
@ 2023-11-02 13:42 ` Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 11/29] UefiCpuPkg: Add CpuMmuLib.h to UefiCpuPkg Chao Li
                   ` (11 subsequent siblings)
  17 siblings, 0 replies; 18+ messages in thread
From: Chao Li @ 2023-11-02 13:42 UTC (permalink / raw)
  To: devel; +Cc: Eric Dong, Ray Ni, Rahul Kumar, Gerd Hoffmann

Add the LoongArch64 CPU Timer library, using CPUCFG 0x4 and 0x5 for
Stable Counter frequency.

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

Cc: Eric Dong <eric.dong@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
Cc: Rahul Kumar <rahul1.kumar@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Chao Li <lichao@loongson.cn>
---
 .../BaseLoongArch64CpuTimerLib.inf            |  30 +++
 .../BaseLoongArch64CpuTimerLib.uni            |  15 ++
 .../BaseLoongArch64CpuTimerLib/CpuTimerLib.c  | 226 ++++++++++++++++++
 UefiCpuPkg/UefiCpuPkg.dsc                     |   3 +
 4 files changed, 274 insertions(+)
 create mode 100644 UefiCpuPkg/Library/BaseLoongArch64CpuTimerLib/BaseLoongArch64CpuTimerLib.inf
 create mode 100644 UefiCpuPkg/Library/BaseLoongArch64CpuTimerLib/BaseLoongArch64CpuTimerLib.uni
 create mode 100644 UefiCpuPkg/Library/BaseLoongArch64CpuTimerLib/CpuTimerLib.c

diff --git a/UefiCpuPkg/Library/BaseLoongArch64CpuTimerLib/BaseLoongArch64CpuTimerLib.inf b/UefiCpuPkg/Library/BaseLoongArch64CpuTimerLib/BaseLoongArch64CpuTimerLib.inf
new file mode 100644
index 0000000000..c00c215aec
--- /dev/null
+++ b/UefiCpuPkg/Library/BaseLoongArch64CpuTimerLib/BaseLoongArch64CpuTimerLib.inf
@@ -0,0 +1,30 @@
+## @file
+#  Base CPU Timer Library
+#
+#  Provides base timer support using CPUCFG 0x4 and 0x5 stable counter frequency.
+#
+#  Copyright (c) 2023, Loongson Technology Corporation Limited. All rights reserved.<BR>
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+  INF_VERSION                       = 0x00010005
+  BASE_NAME                         = BaseLoongArch64CpuTimerLib
+  FILE_GUID                         = 740389C7-CC44-4A2F-88DC-89D97D312E7C
+  MODULE_TYPE                       = BASE
+  VERSION_STRING                    = 1.0
+  LIBRARY_CLASS                     = TimerLib
+  MODULE_UNI_FILE                   = BaseLoongArch64CpuTimerLib.uni
+
+[Sources.common]
+  CpuTimerLib.c
+
+[Packages]
+  MdePkg/MdePkg.dec
+  UefiCpuPkg/UefiCpuPkg.dec
+
+[LibraryClasses]
+  BaseLib
+  PcdLib
+  DebugLib
diff --git a/UefiCpuPkg/Library/BaseLoongArch64CpuTimerLib/BaseLoongArch64CpuTimerLib.uni b/UefiCpuPkg/Library/BaseLoongArch64CpuTimerLib/BaseLoongArch64CpuTimerLib.uni
new file mode 100644
index 0000000000..72d38ec679
--- /dev/null
+++ b/UefiCpuPkg/Library/BaseLoongArch64CpuTimerLib/BaseLoongArch64CpuTimerLib.uni
@@ -0,0 +1,15 @@
+// /** @file
+// Base CPU Timer Library
+//
+// Provides base timer support using CPUCFG 0x4 and 0x5 stable counter frequency.
+//
+// Copyright (c) 2023, Loongson Technology Corporation Limited. All rights reserved.<BR>
+//
+// SPDX-License-Identifier: BSD-2-Clause-Patent
+//
+// **/
+
+
+#string STR_MODULE_ABSTRACT             #language en-US "LOONGARCH CPU Timer Library"
+
+#string STR_MODULE_DESCRIPTION          #language en-US "Provides basic timer support using CPUCFG 0x4 and 0x5 stable counter frequency."
diff --git a/UefiCpuPkg/Library/BaseLoongArch64CpuTimerLib/CpuTimerLib.c b/UefiCpuPkg/Library/BaseLoongArch64CpuTimerLib/CpuTimerLib.c
new file mode 100644
index 0000000000..349b881cbc
--- /dev/null
+++ b/UefiCpuPkg/Library/BaseLoongArch64CpuTimerLib/CpuTimerLib.c
@@ -0,0 +1,226 @@
+/** @file
+  CPUCFG 0x4 and 0x5 for Stable Counter frequency instance of Timer Library.
+
+  Copyright (c) 2023, Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#include <Base.h>
+#include <Library/TimerLib.h>
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Register/LoongArch64/Cpucfg.h>
+
+/**
+  Calculate clock frequency using CPUCFG 0x4 and 0x5 registers.
+
+  @param  VOID.
+
+  @return The frequency in Hz.
+
+**/
+UINT32
+EFIAPI
+CalcConstFreq (
+  VOID
+  )
+{
+  UINT32                 BaseFreq;
+  UINT32                 ClockMultiplier;
+  UINT32                 ClockDivide;
+  CPUCFG_REG4_INFO_DATA  CCFreq;
+  CPUCFG_REG5_INFO_DATA  CpucfgReg5Data;
+  UINT32                 StableTimerFreq;
+
+  //
+  // Get the the crystal frequency corresponding to the constant
+  // frequency timer and the clock used by the timer.
+  //
+  AsmCpucfg (CPUCFG_REG4_INFO, &CCFreq.Uint32);
+
+  //
+  // Get the multiplication factor and frequency division factor
+  // corresponding to the constant frequency timer and the clock
+  // used by the timer.
+  //
+  AsmCpucfg (CPUCFG_REG5_INFO, &CpucfgReg5Data.Uint32);
+
+  BaseFreq        = CCFreq.Bits.CC_FREQ;
+  ClockMultiplier = CpucfgReg5Data.Bits.CC_MUL & 0xFFFFULL;
+  ClockDivide     = CpucfgReg5Data.Bits.CC_DIV & 0xFFFFULL;
+
+  if (!BaseFreq || !ClockMultiplier || !ClockDivide) {
+    DEBUG ((DEBUG_ERROR, "LoongArch Stable Timer is not available in the CPU, hence this library cannot be used.\n"));
+    StableTimerFreq = 0;
+    ASSERT (0);
+  } else {
+    StableTimerFreq = (BaseFreq * ClockMultiplier / ClockDivide);
+  }
+
+  return StableTimerFreq;
+}
+
+/**
+  Stalls the CPU for at least the given number of microseconds.
+
+  Stalls the CPU for the number of microseconds specified by MicroSeconds.
+
+  @param  MicroSeconds  The minimum number of microseconds to delay.
+
+  @return MicroSeconds
+
+**/
+UINTN
+EFIAPI
+MicroSecondDelay (
+  IN UINTN  MicroSeconds
+  )
+{
+  UINTN  Count, Ticks, Start, End;
+
+  Count = (CalcConstFreq () * MicroSeconds) / 1000000;
+  Start = AsmReadStableCounter ();
+  End   = Start + Count;
+
+  do {
+    Ticks = AsmReadStableCounter ();
+  } while (Ticks < End);
+
+  return MicroSeconds;
+}
+
+/**
+  Stalls the CPU for at least the given number of nanoseconds.
+
+  Stalls the CPU for the number of nanoseconds specified by NanoSeconds.
+
+  @param  NanoSeconds The minimum number of nanoseconds to delay.
+
+  @return NanoSeconds
+
+**/
+UINTN
+EFIAPI
+NanoSecondDelay (
+  IN UINTN  NanoSeconds
+  )
+{
+  UINT32  MicroSeconds;
+
+  if (NanoSeconds % 1000 == 0) {
+    MicroSeconds = NanoSeconds/1000;
+  } else {
+    MicroSeconds = NanoSeconds/1000 + 1;
+  }
+
+  MicroSecondDelay (MicroSeconds);
+
+  return NanoSeconds;
+}
+
+/**
+  Retrieves the current value of a 64-bit free running performance counter.
+
+  Retrieves the current value of a 64-bit free running performance counter. The
+  counter can either count up by 1 or count down by 1. If the physical
+  performance counter counts by a larger increment, then the counter values
+  must be translated. The properties of the counter can be retrieved from
+  GetPerformanceCounterProperties().
+
+  @return The current value of the free running performance counter.
+
+**/
+UINT64
+EFIAPI
+GetPerformanceCounter (
+  VOID
+  )
+{
+  return AsmReadStableCounter ();
+}
+
+/**
+  Retrieves the 64-bit frequency in Hz and the range of performance counter
+  values.
+
+  If StartValue is not NULL, then the value that the performance counter starts
+  with immediately after is it rolls over is returned in StartValue. If
+  EndValue is not NULL, then the value that the performance counter end with
+  immediately before it rolls over is returned in EndValue. The 64-bit
+  frequency of the performance counter in Hz is always returned. If StartValue
+  is less than EndValue, then the performance counter counts up. If StartValue
+  is greater than EndValue, then the performance counter counts down. For
+  example, a 64-bit free running counter that counts up would have a StartValue
+  of 0 and an EndValue of 0xFFFFFFFFFFFFFFFF. A 24-bit free running counter
+  that counts down would have a StartValue of 0xFFFFFF and an EndValue of 0.
+
+  @param  StartValue  The value the performance counter starts with when it
+                      rolls over.
+  @param  EndValue    The value that the performance counter ends with before
+                      it rolls over.
+
+  @return The frequency in Hz.
+
+**/
+UINT64
+EFIAPI
+GetPerformanceCounterProperties (
+  OUT UINT64  *StartValue   OPTIONAL,
+  OUT UINT64  *EndValue     OPTIONAL
+  )
+{
+  if (StartValue != NULL) {
+    *StartValue = BIT2;
+  }
+
+  if (EndValue != NULL) {
+    *EndValue = BIT48 - 1;
+  }
+
+  return CalcConstFreq ();
+}
+
+/**
+  Converts elapsed ticks of performance counter to time in nanoseconds.
+
+  This function converts the elapsed ticks of running performance counter to
+  time value in unit of nanoseconds.
+
+  @param  Ticks     The number of elapsed ticks of running performance counter.
+
+  @return The elapsed time in nanoseconds.
+
+**/
+UINT64
+EFIAPI
+GetTimeInNanoSecond (
+  IN UINT64  Ticks
+  )
+{
+  UINT64  Frequency;
+  UINT64  NanoSeconds;
+  UINT64  Remainder;
+  INTN    Shift;
+
+  Frequency = GetPerformanceCounterProperties (NULL, NULL);
+
+  //
+  //          Ticks
+  // Time = --------- x 1,000,000,000
+  //        Frequency
+  //
+  NanoSeconds = MultU64x32 (DivU64x64Remainder (Ticks, Frequency, &Remainder), 1000000000u);
+
+  //
+  // Ensure (Remainder * 1,000,000,000) will not overflow 64-bit.
+  // Since 2^29 < 1,000,000,000 = 0x3B9ACA00 < 2^30, Remainder should < 2^(64-30) = 2^34,
+  // i.e. highest bit set in Remainder should <= 33.
+  //
+  Shift        = MAX (0, HighBitSet64 (Remainder) - 33);
+  Remainder    = RShiftU64 (Remainder, (UINTN)Shift);
+  Frequency    = RShiftU64 (Frequency, (UINTN)Shift);
+  NanoSeconds += DivU64x64Remainder (MultU64x32 (Remainder, 1000000000u), Frequency, NULL);
+
+  return NanoSeconds;
+}
diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc
index 074fd77461..8e34a9cd6b 100644
--- a/UefiCpuPkg/UefiCpuPkg.dsc
+++ b/UefiCpuPkg/UefiCpuPkg.dsc
@@ -205,5 +205,8 @@
   UefiCpuPkg/CpuTimerDxeRiscV64/CpuTimerDxeRiscV64.inf
   UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf
 
+[Components.LOONGARCH64]
+  UefiCpuPkg/Library/BaseLoongArch64CpuTimerLib/BaseLoongArch64CpuTimerLib.inf
+
 [BuildOptions]
   *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES
-- 
2.27.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#110536): https://edk2.groups.io/g/devel/message/110536
Mute This Topic: https://groups.io/mt/102342225/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* [edk2-devel] [PATCH v1 11/29] UefiCpuPkg: Add CpuMmuLib.h to UefiCpuPkg
       [not found] <20231102134249.3983594-1-lichao@loongson.cn>
                   ` (5 preceding siblings ...)
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 09/29] UefiCpuPkg: Add LoongArch64 CPU Timer library Chao Li
@ 2023-11-02 13:42 ` Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 15/29] EmbeddedPkg: Add PcdPrePiCpuIoSize width for LOONGARCH64 Chao Li
                   ` (10 subsequent siblings)
  17 siblings, 0 replies; 18+ messages in thread
From: Chao Li @ 2023-11-02 13:42 UTC (permalink / raw)
  To: devel
  Cc: Eric Dong, Ray Ni, Rahul Kumar, Gerd Hoffmann, Leif Lindholm,
	Ard Biesheuvel, Sami Mujawar, Sunil V L, Andrei Warkentin

Add a new header file CpuMmuLib.h, whitch is referenced from
ArmPkg/Include/Library/ArmMmuLib.h. Currently, only support for
LoongArch64 is added, and more architectures can be accommodated in the
future.

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

Cc: Eric Dong <eric.dong@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
Cc: Rahul Kumar <rahul1.kumar@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Leif Lindholm <quic_llindhol@quicinc.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Sami Mujawar <sami.mujawar@arm.com>
Cc: Sunil V L <sunilvl@ventanamicro.com>
Cc: Andrei Warkentin <andrei.warkentin@intel.com>
Signed-off-by: Chao Li <lichao@loongson.cn>
---
 UefiCpuPkg/Include/Library/CpuMmuLib.h | 194 +++++++++++++++++++++++++
 UefiCpuPkg/UefiCpuPkg.dec              |   4 +
 2 files changed, 198 insertions(+)
 create mode 100644 UefiCpuPkg/Include/Library/CpuMmuLib.h

diff --git a/UefiCpuPkg/Include/Library/CpuMmuLib.h b/UefiCpuPkg/Include/Library/CpuMmuLib.h
new file mode 100644
index 0000000000..8f524d31d4
--- /dev/null
+++ b/UefiCpuPkg/Include/Library/CpuMmuLib.h
@@ -0,0 +1,194 @@
+/** @file
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef CPU_MMU_LIB_H_
+#define CPU_MMU_LIB_H_
+
+#include <Uefi/UefiBaseType.h>
+
+#ifdef MDE_CPU_LOONGARCH64
+
+/* 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
+
+#define EFI_MEMORY_CACHETYPE_MASK  (EFI_MEMORY_UC  | \
+                                    EFI_MEMORY_WC  | \
+                                    EFI_MEMORY_WT  | \
+                                    EFI_MEMORY_WB  | \
+                                    EFI_MEMORY_UCE   \
+                                    )
+#endif
+
+typedef struct {
+  EFI_PHYSICAL_ADDRESS    PhysicalBase;
+  EFI_VIRTUAL_ADDRESS     VirtualBase;
+  UINTN                   Length;
+  UINTN                   Attributes;
+} MEMORY_REGION_DESCRIPTOR;
+
+/**
+  Converts EFI Attributes to corresponding architecture Attributes.
+
+  @param[in]  EfiAttributes     Efi Attributes.
+
+  @retval  Corresponding architecture attributes.
+**/
+UINTN
+EfiAttributeConverse (
+  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
+GetMemoryRegionAttribute (
+  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
+SetMemoryAttributes (
+  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
+SetMemoryRegionNoExec (
+  IN  EFI_PHYSICAL_ADDRESS  BaseAddress,
+  IN  UINTN                 Length
+  );
+
+/**
+  Clears the non-executable Attributes for the specified memory region
+
+  @param[in]  BaseAddress  The base address of the memory region to clear the Attributes.
+  @param[in]  Length       The length of the memory region to clear the Attributes.
+
+  @retval  EFI_SUCCESS    The Attributes was clear successfully
+**/
+EFI_STATUS
+EFIAPI
+ClearMemoryRegionNoExec (
+  IN  EFI_PHYSICAL_ADDRESS  BaseAddress,
+  IN  UINT64                Length
+  );
+
+/**
+  Sets the read-only 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
+EFIAPI
+SetMemoryRegionReadOnly (
+  IN  EFI_PHYSICAL_ADDRESS  BaseAddress,
+  IN  UINT64                Length
+  );
+
+/**
+  Clears the read-only Attributes for the specified memory region
+
+  @param[in]  BaseAddress  The base address of the memory region to clear the Attributes.
+  @param[in]  Length       The length of the memory region to clear the Attributes.
+
+  @retval  EFI_SUCCESS    The Attributes was clear successfully
+**/
+EFI_STATUS
+EFIAPI
+ClearMemoryRegionReadOnly (
+  IN  EFI_PHYSICAL_ADDRESS  BaseAddress,
+  IN  UINT64                Length
+  );
+
+/**
+  Create a page table and initialize the memory management unit(MMU).
+
+  @param[in]     MemoryTable           A pointer to a memory ragion table.
+  @param[out]    TranslationTableBase  A pointer to a translation table base address.
+  @param[in out] TranslationTableSize  A pointer to a translation table base size.
+
+  @retval  EFI_SUCCESS                Configure MMU successfully.
+           EFI_INVALID_PARAMETER      MemoryTable is NULL.
+           EFI_UNSUPPORTED            Out of memory space or size not aligned.
+**/
+EFI_STATUS
+EFIAPI
+ConfigureMemoryManagementUint (
+  IN     MEMORY_REGION_DESCRIPTOR  *MemoryTable,
+  OUT    VOID                      **TranslationTableBase OPTIONAL,
+  IN OUT UINTN                     *TranslationTableSize  OPTIONAL
+  );
+
+#endif // CPU_MMU_LIB_H_
diff --git a/UefiCpuPkg/UefiCpuPkg.dec b/UefiCpuPkg/UefiCpuPkg.dec
index 154b1d06fe..150beae981 100644
--- a/UefiCpuPkg/UefiCpuPkg.dec
+++ b/UefiCpuPkg/UefiCpuPkg.dec
@@ -62,6 +62,10 @@
   ##  @libraryclass  Provides function for manipulating x86 paging structures.
   CpuPageTableLib|Include/Library/CpuPageTableLib.h
 
+[LibraryClasses.LoongArch64]
+  ##  @libraryclass  Provides macros and functions for the memory management unit.
+  CpuMmuLib|Include/Library/CpuMmuLib.h
+
   ## @libraryclass   Provides functions for manipulating smram savestate registers.
   MmSaveStateLib|Include/Library/MmSaveStateLib.h
 
-- 
2.27.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#110529): https://edk2.groups.io/g/devel/message/110529
Mute This Topic: https://groups.io/mt/102342169/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* [edk2-devel] [PATCH v1 15/29] EmbeddedPkg: Add PcdPrePiCpuIoSize width for LOONGARCH64
       [not found] <20231102134249.3983594-1-lichao@loongson.cn>
                   ` (6 preceding siblings ...)
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 11/29] UefiCpuPkg: Add CpuMmuLib.h to UefiCpuPkg Chao Li
@ 2023-11-02 13:42 ` Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 16/29] ArmVirtPkg: Move PCD of FDT base address and FDT padding to OvmfPkg Chao Li
                   ` (9 subsequent siblings)
  17 siblings, 0 replies; 18+ messages in thread
From: Chao Li @ 2023-11-02 13:42 UTC (permalink / raw)
  To: devel; +Cc: Leif Lindholm, Ard Biesheuvel, Abner Chang, Daniel Schaefer

Added LoongArch64 architecture CPU IO width.

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

Cc: Leif Lindholm <quic_llindhol@quicinc.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Abner Chang <abner.chang@amd.com>
Cc: Daniel Schaefer <git@danielschaefer.me>
Signed-off-by: Chao Li <lichao@loongson.cn>
---
 EmbeddedPkg/EmbeddedPkg.dec | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/EmbeddedPkg/EmbeddedPkg.dec b/EmbeddedPkg/EmbeddedPkg.dec
index 341ef5e6a6..241d4f3acc 100644
--- a/EmbeddedPkg/EmbeddedPkg.dec
+++ b/EmbeddedPkg/EmbeddedPkg.dec
@@ -165,6 +165,9 @@
 [PcdsFixedAtBuild.X64]
   gEmbeddedTokenSpaceGuid.PcdPrePiCpuIoSize|16|UINT8|0x00000011
 
+[PcdsFixedAtBuild.LOONGARCH64]
+  gEmbeddedTokenSpaceGuid.PcdPrePiCpuIoSize|16|UINT8|0x00000011
+
 [PcdsFixedAtBuild.common, PcdsDynamic.common]
   #
   # Value to add to a host address to obtain a device address, using
-- 
2.27.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#110545): https://edk2.groups.io/g/devel/message/110545
Mute This Topic: https://groups.io/mt/102342339/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* [edk2-devel] [PATCH v1 16/29] ArmVirtPkg: Move PCD of FDT base address and FDT padding to OvmfPkg
       [not found] <20231102134249.3983594-1-lichao@loongson.cn>
                   ` (7 preceding siblings ...)
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 15/29] EmbeddedPkg: Add PcdPrePiCpuIoSize width for LOONGARCH64 Chao Li
@ 2023-11-02 13:42 ` Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 17/29] OvmfPkg/LoongArchVirt: Add PciCpuIo2Dxe module Chao Li
                   ` (8 subsequent siblings)
  17 siblings, 0 replies; 18+ messages in thread
From: Chao Li @ 2023-11-02 13:42 UTC (permalink / raw)
  To: devel
  Cc: Ard Biesheuvel, Leif Lindholm, Sami Mujawar, Gerd Hoffmann,
	Jiewen Yao, Jordan Justen

Moved PcdDeviceTreeInitialBaseAddress and PcdDeviceTreeAllocationPadding
to OvmfPkg for easier use by other architectures.

Build-tested only (with "ArmVirtQemu.dsc").

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

Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Leif Lindholm <quic_llindhol@quicinc.com>
Cc: Sami Mujawar <sami.mujawar@arm.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Signed-off-by: Chao Li <lichao@loongson.cn>
---
 ArmVirtPkg/ArmVirtCloudHv.dsc                     |  2 +-
 ArmVirtPkg/ArmVirtKvmTool.dsc                     |  2 +-
 ArmVirtPkg/ArmVirtPkg.dec                         | 14 --------------
 ArmVirtPkg/ArmVirtQemu.dsc                        |  2 +-
 ArmVirtPkg/ArmVirtQemuKernel.dsc                  |  2 +-
 ArmVirtPkg/ArmVirtXen.dsc                         |  2 +-
 .../ArmVirtPsciResetSystemPeiLib.inf              |  3 ++-
 .../CloudHvVirtMemInfoPeiLib.inf                  |  3 ++-
 .../DebugLibFdtPL011UartFlash.inf                 |  3 ++-
 .../EarlyFdt16550SerialPortHookLib.inf            |  3 ++-
 .../EarlyFdtPL011SerialPortLib.inf                |  3 ++-
 .../KvmtoolPlatformPeiLib.inf                     |  5 +++--
 .../Library/PlatformPeiLib/PlatformPeiLib.inf     | 10 +++++-----
 .../QemuVirtMemInfoLib/QemuVirtMemInfoPeiLib.inf  |  3 ++-
 .../PrePi/ArmVirtPrePiUniCoreRelocatable.inf      |  3 ++-
 OvmfPkg/OvmfPkg.dec                               | 15 +++++++++++++++
 16 files changed, 42 insertions(+), 33 deletions(-)

diff --git a/ArmVirtPkg/ArmVirtCloudHv.dsc b/ArmVirtPkg/ArmVirtCloudHv.dsc
index 2cb89ce10c..76c0d28544 100644
--- a/ArmVirtPkg/ArmVirtCloudHv.dsc
+++ b/ArmVirtPkg/ArmVirtCloudHv.dsc
@@ -129,7 +129,7 @@
   gArmTokenSpaceGuid.PcdSystemMemoryBase|0x40000000
 
   # initial location of the device tree blob passed by Cloud Hypervisor -- base of DRAM
-  gArmVirtTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress|0x40000000
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress|0x40000000
 
   gEfiMdeModulePkgTokenSpaceGuid.PcdResetOnMemoryTypeInformationChange|FALSE
   gEfiMdeModulePkgTokenSpaceGuid.PcdBootManagerMenuFile|{ 0x21, 0xaa, 0x2c, 0x46, 0x14, 0x76, 0x03, 0x45, 0x83, 0x6e, 0x8a, 0xb6, 0xf4, 0x66, 0x23, 0x31 }
diff --git a/ArmVirtPkg/ArmVirtKvmTool.dsc b/ArmVirtPkg/ArmVirtKvmTool.dsc
index f50d53bf15..cac4fe06d3 100644
--- a/ArmVirtPkg/ArmVirtKvmTool.dsc
+++ b/ArmVirtPkg/ArmVirtKvmTool.dsc
@@ -179,7 +179,7 @@
   # We are booting from RAM using the Linux kernel boot protocol,
   # x0 will point to the DTB image in memory.
   #
-  gArmVirtTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress|0x0
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress|0x0
 
   gArmTokenSpaceGuid.PcdFdBaseAddress|0x0
   gArmTokenSpaceGuid.PcdFvBaseAddress|0x0
diff --git a/ArmVirtPkg/ArmVirtPkg.dec b/ArmVirtPkg/ArmVirtPkg.dec
index 0f2d787327..2451644844 100644
--- a/ArmVirtPkg/ArmVirtPkg.dec
+++ b/ArmVirtPkg/ArmVirtPkg.dec
@@ -42,20 +42,6 @@
   gArmVirtTokenSpaceGuid.PcdTpm2SupportEnabled|FALSE|BOOLEAN|0x00000004
 
 [PcdsFixedAtBuild, PcdsPatchableInModule]
-  #
-  # This is the physical address where the device tree is expected to be stored
-  # upon first entry into UEFI. This needs to be a FixedAtBuild PCD, so that we
-  # can do a first pass over the device tree in the SEC phase to discover the
-  # UART base address.
-  #
-  gArmVirtTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress|0x0|UINT64|0x00000001
-
-  #
-  # Padding in bytes to add to the device tree allocation, so that the DTB can
-  # be modified in place (default: 256 bytes)
-  #
-  gArmVirtTokenSpaceGuid.PcdDeviceTreeAllocationPadding|256|UINT32|0x00000002
-
   #
   # Binary representation of the GUID that determines the terminal type. The
   # size must be exactly 16 bytes. The default value corresponds to
diff --git a/ArmVirtPkg/ArmVirtQemu.dsc b/ArmVirtPkg/ArmVirtQemu.dsc
index 30e3cfc8b9..cf306cac08 100644
--- a/ArmVirtPkg/ArmVirtQemu.dsc
+++ b/ArmVirtPkg/ArmVirtQemu.dsc
@@ -201,7 +201,7 @@
   gArmTokenSpaceGuid.PcdSystemMemoryBase|0x40000000
 
   # initial location of the device tree blob passed by QEMU -- base of DRAM
-  gArmVirtTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress|0x40000000
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress|0x40000000
 
   gEfiMdeModulePkgTokenSpaceGuid.PcdResetOnMemoryTypeInformationChange|FALSE
   gEfiMdeModulePkgTokenSpaceGuid.PcdBootManagerMenuFile|{ 0x21, 0xaa, 0x2c, 0x46, 0x14, 0x76, 0x03, 0x45, 0x83, 0x6e, 0x8a, 0xb6, 0xf4, 0x66, 0x23, 0x31 }
diff --git a/ArmVirtPkg/ArmVirtQemuKernel.dsc b/ArmVirtPkg/ArmVirtQemuKernel.dsc
index b50f8e84a3..c0d079e28d 100644
--- a/ArmVirtPkg/ArmVirtQemuKernel.dsc
+++ b/ArmVirtPkg/ArmVirtQemuKernel.dsc
@@ -198,7 +198,7 @@
   # Define a default initial address for the device tree.
   # Ignored if x0 != 0 at entry.
   #
-  gArmVirtTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress|0x40000000
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress|0x40000000
 
   gArmTokenSpaceGuid.PcdFdBaseAddress|0x0
   gArmTokenSpaceGuid.PcdFvBaseAddress|0x0
diff --git a/ArmVirtPkg/ArmVirtXen.dsc b/ArmVirtPkg/ArmVirtXen.dsc
index f0d15b823b..5809832e66 100644
--- a/ArmVirtPkg/ArmVirtXen.dsc
+++ b/ArmVirtPkg/ArmVirtXen.dsc
@@ -115,7 +115,7 @@
   #
   gArmTokenSpaceGuid.PcdSystemMemoryBase|0x0
   gArmTokenSpaceGuid.PcdSystemMemorySize|0x0
-  gArmVirtTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress|0x0
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress|0x0
 
   gArmTokenSpaceGuid.PcdFdBaseAddress|0x0
   gArmTokenSpaceGuid.PcdFvBaseAddress|0x0
diff --git a/ArmVirtPkg/Library/ArmVirtPsciResetSystemPeiLib/ArmVirtPsciResetSystemPeiLib.inf b/ArmVirtPkg/Library/ArmVirtPsciResetSystemPeiLib/ArmVirtPsciResetSystemPeiLib.inf
index 3a65706e8d..79217d296d 100644
--- a/ArmVirtPkg/Library/ArmVirtPsciResetSystemPeiLib/ArmVirtPsciResetSystemPeiLib.inf
+++ b/ArmVirtPkg/Library/ArmVirtPsciResetSystemPeiLib/ArmVirtPsciResetSystemPeiLib.inf
@@ -26,6 +26,7 @@
   EmbeddedPkg/EmbeddedPkg.dec
   MdeModulePkg/MdeModulePkg.dec
   MdePkg/MdePkg.dec
+  OvmfPkg/OvmfPkg.dec
 
 [LibraryClasses]
   ArmSmcLib
@@ -36,4 +37,4 @@
   HobLib
 
 [Pcd]
-  gArmVirtTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress
diff --git a/ArmVirtPkg/Library/CloudHvVirtMemInfoLib/CloudHvVirtMemInfoPeiLib.inf b/ArmVirtPkg/Library/CloudHvVirtMemInfoLib/CloudHvVirtMemInfoPeiLib.inf
index 666b5d9711..6df26ccd64 100644
--- a/ArmVirtPkg/Library/CloudHvVirtMemInfoLib/CloudHvVirtMemInfoPeiLib.inf
+++ b/ArmVirtPkg/Library/CloudHvVirtMemInfoLib/CloudHvVirtMemInfoPeiLib.inf
@@ -26,6 +26,7 @@
   EmbeddedPkg/EmbeddedPkg.dec
   MdeModulePkg/MdeModulePkg.dec
   MdePkg/MdePkg.dec
+  OvmfPkg/OvmfPkg.dec
 
 [LibraryClasses]
   ArmLib
@@ -44,4 +45,4 @@
 [FixedPcd]
   gArmTokenSpaceGuid.PcdFdSize
   gArmTokenSpaceGuid.PcdFvSize
-  gArmVirtTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress
diff --git a/ArmVirtPkg/Library/DebugLibFdtPL011Uart/DebugLibFdtPL011UartFlash.inf b/ArmVirtPkg/Library/DebugLibFdtPL011Uart/DebugLibFdtPL011UartFlash.inf
index 7870ca2ae4..f35a0913f0 100644
--- a/ArmVirtPkg/Library/DebugLibFdtPL011Uart/DebugLibFdtPL011UartFlash.inf
+++ b/ArmVirtPkg/Library/DebugLibFdtPL011Uart/DebugLibFdtPL011UartFlash.inf
@@ -30,6 +30,7 @@
   ArmPlatformPkg/ArmPlatformPkg.dec
   ArmVirtPkg/ArmVirtPkg.dec
   MdePkg/MdePkg.dec
+  OvmfPkg/OvmfPkg.dec
 
 [LibraryClasses]
   BaseLib
@@ -41,7 +42,7 @@
   PrintLib
 
 [Pcd]
-  gArmVirtTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress # Flash.c
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress # Flash.c
   gEfiMdePkgTokenSpaceGuid.PcdDebugClearMemoryValue
   gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask
   gEfiMdePkgTokenSpaceGuid.PcdFixedDebugPrintErrorLevel
diff --git a/ArmVirtPkg/Library/Fdt16550SerialPortHookLib/EarlyFdt16550SerialPortHookLib.inf b/ArmVirtPkg/Library/Fdt16550SerialPortHookLib/EarlyFdt16550SerialPortHookLib.inf
index 22aba53d9b..3e2303b7f4 100644
--- a/ArmVirtPkg/Library/Fdt16550SerialPortHookLib/EarlyFdt16550SerialPortHookLib.inf
+++ b/ArmVirtPkg/Library/Fdt16550SerialPortHookLib/EarlyFdt16550SerialPortHookLib.inf
@@ -29,7 +29,8 @@
   ArmVirtPkg/ArmVirtPkg.dec
   MdeModulePkg/MdeModulePkg.dec
   MdePkg/MdePkg.dec
+  OvmfPkg/OvmfPkg.dec
 
 [Pcd]
-  gArmVirtTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress
   gEfiMdeModulePkgTokenSpaceGuid.PcdSerialRegisterBase
diff --git a/ArmVirtPkg/Library/FdtPL011SerialPortLib/EarlyFdtPL011SerialPortLib.inf b/ArmVirtPkg/Library/FdtPL011SerialPortLib/EarlyFdtPL011SerialPortLib.inf
index f47692f06a..e677f1d9e7 100644
--- a/ArmVirtPkg/Library/FdtPL011SerialPortLib/EarlyFdtPL011SerialPortLib.inf
+++ b/ArmVirtPkg/Library/FdtPL011SerialPortLib/EarlyFdtPL011SerialPortLib.inf
@@ -28,9 +28,10 @@
   MdePkg/MdePkg.dec
   ArmPlatformPkg/ArmPlatformPkg.dec
   ArmVirtPkg/ArmVirtPkg.dec
+  OvmfPkg/OvmfPkg.dec
 
 [Pcd]
-  gArmVirtTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress
 
 [FixedPcd]
   gEfiMdePkgTokenSpaceGuid.PcdUartDefaultBaudRate
diff --git a/ArmVirtPkg/Library/KvmtoolPlatformPeiLib/KvmtoolPlatformPeiLib.inf b/ArmVirtPkg/Library/KvmtoolPlatformPeiLib/KvmtoolPlatformPeiLib.inf
index f201aee50c..78c9d9d764 100644
--- a/ArmVirtPkg/Library/KvmtoolPlatformPeiLib/KvmtoolPlatformPeiLib.inf
+++ b/ArmVirtPkg/Library/KvmtoolPlatformPeiLib/KvmtoolPlatformPeiLib.inf
@@ -24,6 +24,7 @@
   EmbeddedPkg/EmbeddedPkg.dec
   MdeModulePkg/MdeModulePkg.dec
   MdePkg/MdePkg.dec
+  OvmfPkg/OvmfPkg.dec
 
 [LibraryClasses]
   DebugLib
@@ -34,11 +35,11 @@
 
 [FixedPcd]
   gArmTokenSpaceGuid.PcdFvSize
-  gArmVirtTokenSpaceGuid.PcdDeviceTreeAllocationPadding
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeAllocationPadding
 
 [Pcd]
   gArmTokenSpaceGuid.PcdFvBaseAddress
-  gArmVirtTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress
   gEfiMdeModulePkgTokenSpaceGuid.PcdSerialRegisterBase
 
 [Guids]
diff --git a/ArmVirtPkg/Library/PlatformPeiLib/PlatformPeiLib.inf b/ArmVirtPkg/Library/PlatformPeiLib/PlatformPeiLib.inf
index b867d8bb89..0584a53ee3 100644
--- a/ArmVirtPkg/Library/PlatformPeiLib/PlatformPeiLib.inf
+++ b/ArmVirtPkg/Library/PlatformPeiLib/PlatformPeiLib.inf
@@ -41,16 +41,16 @@
 
 [FixedPcd]
   gArmTokenSpaceGuid.PcdFvSize
-  gArmVirtTokenSpaceGuid.PcdDeviceTreeAllocationPadding
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeAllocationPadding
 
 [Pcd]
   gArmTokenSpaceGuid.PcdFvBaseAddress
-  gArmVirtTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress
-  gEfiSecurityPkgTokenSpaceGuid.PcdTpmBaseAddress         ## SOMETIMES_PRODUCES
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress
+  gEfiSecurityPkgTokenSpaceGuid.PcdTpmBaseAddress             ## SOMETIMES_PRODUCES
 
 [Ppis]
-  gOvmfTpmDiscoveredPpiGuid                               ## SOMETIMES_PRODUCES
-  gPeiTpmInitializationDonePpiGuid                        ## SOMETIMES_PRODUCES
+  gOvmfTpmDiscoveredPpiGuid                                   ## SOMETIMES_PRODUCES
+  gPeiTpmInitializationDonePpiGuid                            ## SOMETIMES_PRODUCES
 
 [Guids]
   gEarlyPL011BaseAddressGuid
diff --git a/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLib.inf b/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLib.inf
index f045e39a41..76c3c5d3c8 100644
--- a/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLib.inf
+++ b/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLib.inf
@@ -26,6 +26,7 @@
   EmbeddedPkg/EmbeddedPkg.dec
   MdeModulePkg/MdeModulePkg.dec
   MdePkg/MdePkg.dec
+  OvmfPkg/OvmfPkg.dec
 
 [LibraryClasses]
   ArmLib
@@ -44,4 +45,4 @@
   gArmTokenSpaceGuid.PcdSystemMemorySize
   gArmTokenSpaceGuid.PcdFdSize
   gArmTokenSpaceGuid.PcdFvSize
-  gArmVirtTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress
diff --git a/ArmVirtPkg/PrePi/ArmVirtPrePiUniCoreRelocatable.inf b/ArmVirtPkg/PrePi/ArmVirtPrePiUniCoreRelocatable.inf
index 7edf501808..691fc26350 100755
--- a/ArmVirtPkg/PrePi/ArmVirtPrePiUniCoreRelocatable.inf
+++ b/ArmVirtPkg/PrePi/ArmVirtPrePiUniCoreRelocatable.inf
@@ -32,6 +32,7 @@
   MdePkg/MdePkg.dec
   MdeModulePkg/MdeModulePkg.dec
   EmbeddedPkg/EmbeddedPkg.dec
+  OvmfPkg/OvmfPkg.dec
   ArmPkg/ArmPkg.dec
   ArmPlatformPkg/ArmPlatformPkg.dec
   ArmVirtPkg/ArmVirtPkg.dec
@@ -93,6 +94,6 @@
 [Pcd]
   gArmTokenSpaceGuid.PcdSystemMemoryBase
   gArmTokenSpaceGuid.PcdSystemMemorySize
-  gArmVirtTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress
   gArmTokenSpaceGuid.PcdFdBaseAddress
   gArmTokenSpaceGuid.PcdFvBaseAddress
diff --git a/OvmfPkg/OvmfPkg.dec b/OvmfPkg/OvmfPkg.dec
index e3861e5c1b..89091e8bf1 100644
--- a/OvmfPkg/OvmfPkg.dec
+++ b/OvmfPkg/OvmfPkg.dec
@@ -481,6 +481,21 @@
   #
   gUefiOvmfPkgTokenSpaceGuid.PcdForceNoAcpi|0x0|BOOLEAN|0x69
 
+[PcdsFixedAtBuild, PcdsPatchableInModule]
+  #
+  # This is the physical address where the device tree is expected to be stored
+  # upon first entry into UEFI. This needs to be a FixedAtBuild PCD, so that we
+  # can do a first pass over the device tree in the SEC phase to discover the
+  # UART base address.
+  #
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress|0x0|UINT64|0x6e
+
+  #
+  # Padding in bytes to add to the device tree allocation, so that the DTB can
+  # be modified in place (default: 256 bytes)
+  #
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeAllocationPadding|256|UINT32|0x6f
+
 [PcdsFeatureFlag]
   gUefiOvmfPkgTokenSpaceGuid.PcdQemuBootOrderPciTranslation|TRUE|BOOLEAN|0x1c
   gUefiOvmfPkgTokenSpaceGuid.PcdQemuBootOrderMmioTranslation|FALSE|BOOLEAN|0x1d
-- 
2.27.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#110538): https://edk2.groups.io/g/devel/message/110538
Mute This Topic: https://groups.io/mt/102342249/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* [edk2-devel] [PATCH v1 17/29] OvmfPkg/LoongArchVirt: Add PciCpuIo2Dxe module
       [not found] <20231102134249.3983594-1-lichao@loongson.cn>
                   ` (8 preceding siblings ...)
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 16/29] ArmVirtPkg: Move PCD of FDT base address and FDT padding to OvmfPkg Chao Li
@ 2023-11-02 13:42 ` Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 18/29] OvmfPkg/LoongArchVirt: Add stable timer driver Chao Li
                   ` (7 subsequent siblings)
  17 siblings, 0 replies; 18+ messages in thread
From: Chao Li @ 2023-11-02 13:42 UTC (permalink / raw)
  To: devel
  Cc: Ard Biesheuvel, Jiewen Yao, Jordan Justen, Gerd Hoffmann,
	Xianglai Li, Bibo Mao

Add PciCpuIo2Dxe for LoongArch, this module is similar to
ArmPciCpuIo2Dxe drvier.

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

Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Chao Li <lichao@loongson.cn>
Co-authored-by: Xianglai Li <lixianglai@loongson.cn>
Co-authored-by: Bibo Mao <maobibo@loongson.cn>
---
 .../Drivers/PciCpuIo2Dxe/PciCpuIo2Dxe.c       | 547 ++++++++++++++++++
 .../Drivers/PciCpuIo2Dxe/PciCpuIo2Dxe.inf     |  45 ++
 2 files changed, 592 insertions(+)
 create mode 100644 OvmfPkg/LoongArchVirt/Drivers/PciCpuIo2Dxe/PciCpuIo2Dxe.c
 create mode 100644 OvmfPkg/LoongArchVirt/Drivers/PciCpuIo2Dxe/PciCpuIo2Dxe.inf

diff --git a/OvmfPkg/LoongArchVirt/Drivers/PciCpuIo2Dxe/PciCpuIo2Dxe.c b/OvmfPkg/LoongArchVirt/Drivers/PciCpuIo2Dxe/PciCpuIo2Dxe.c
new file mode 100644
index 0000000000..626a39ae26
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Drivers/PciCpuIo2Dxe/PciCpuIo2Dxe.c
@@ -0,0 +1,547 @@
+/** @file
+  Produces the CPU I/O 2 Protocol.
+
+  Copyright (c) 2009 - 2012, Intel Corporation. All rights reserved.<BR>
+  Copyright (c) 2016, Linaro Ltd. All rights reserved.<BR>
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <PiDxe.h>
+
+#include <Protocol/CpuIo2.h>
+
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/IoLib.h>
+#include <Library/PcdLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+
+#define MAX_IO_PORT_ADDRESS  0xFFFF
+
+//
+// Handle for the CPU I/O 2 Protocol
+//
+STATIC EFI_HANDLE  mHandle = NULL;
+
+//
+// Lookup table for increment values based on transfer widths
+//
+STATIC CONST UINT8  mInStride[] = {
+  1, // EfiCpuIoWidthUint8
+  2, // EfiCpuIoWidthUint16
+  4, // EfiCpuIoWidthUint32
+  8, // EfiCpuIoWidthUint64
+  0, // EfiCpuIoWidthFifoUint8
+  0, // EfiCpuIoWidthFifoUint16
+  0, // EfiCpuIoWidthFifoUint32
+  0, // EfiCpuIoWidthFifoUint64
+  1, // EfiCpuIoWidthFillUint8
+  2, // EfiCpuIoWidthFillUint16
+  4, // EfiCpuIoWidthFillUint32
+  8  // EfiCpuIoWidthFillUint64
+};
+
+//
+// Lookup table for increment values based on transfer widths
+//
+STATIC CONST UINT8  mOutStride[] = {
+  1, // EfiCpuIoWidthUint8
+  2, // EfiCpuIoWidthUint16
+  4, // EfiCpuIoWidthUint32
+  8, // EfiCpuIoWidthUint64
+  1, // EfiCpuIoWidthFifoUint8
+  2, // EfiCpuIoWidthFifoUint16
+  4, // EfiCpuIoWidthFifoUint32
+  8, // EfiCpuIoWidthFifoUint64
+  0, // EfiCpuIoWidthFillUint8
+  0, // EfiCpuIoWidthFillUint16
+  0, // EfiCpuIoWidthFillUint32
+  0  // EfiCpuIoWidthFillUint64
+};
+
+/**
+  Check parameters to a CPU I/O 2 Protocol service request.
+
+  The I/O operations are carried out exactly as requested. The caller is responsible
+  for satisfying any alignment and I/O width restrictions that a PI System on a
+  platform might require. For example on some platforms, width requests of
+  EfiCpuIoWidthUint64 do not work. Misaligned buffers, on the other hand, will
+  be handled by the driver.
+
+  @param[in] MmioOperation  TRUE for an MMIO operation, FALSE for I/O Port operation.
+  @param[in] Width          Signifies the width of the I/O or Memory operation.
+  @param[in] Address        The base address of the I/O operation.
+  @param[in] Count          The number of I/O operations to perform. The number of
+                            bytes moved is Width size * Count, starting at Address.
+  @param[in] Buffer         For read operations, the destination buffer to store the results.
+                            For write operations, the source buffer from which to write data.
+
+  @retval EFI_SUCCESS            The parameters for this request pass the checks.
+  @retval EFI_INVALID_PARAMETER  Width is invalid for this PI system.
+  @retval EFI_INVALID_PARAMETER  Buffer is NULL.
+  @retval EFI_UNSUPPORTED        The Buffer is not aligned for the given Width.
+  @retval EFI_UNSUPPORTED        The address range specified by Address, Width,
+                                 and Count is not valid for this PI system.
+**/
+EFI_STATUS
+CpuIoCheckParameter (
+  IN BOOLEAN                    MmioOperation,
+  IN EFI_CPU_IO_PROTOCOL_WIDTH  Width,
+  IN UINT64                     Address,
+  IN UINTN                      Count,
+  IN VOID                       *Buffer
+  )
+{
+  UINT64  MaxCount;
+  UINT64  Limit;
+
+  //
+  // Check to see if Buffer is NULL
+  //
+  if (Buffer == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  //
+  // Check to see if Width is in the valid range
+  //
+  if ((UINT32)Width >= EfiCpuIoWidthMaximum) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  //
+  // For FIFO type, the target address won't increase during the access,
+  // so treat Count as 1
+  //
+  if ((Width >= EfiCpuIoWidthFifoUint8) && (Width <= EfiCpuIoWidthFifoUint64)) {
+    Count = 1;
+  }
+
+  //
+  // Check to see if Width is in the valid range for I/O Port operations
+  //
+  Width = (EFI_CPU_IO_PROTOCOL_WIDTH)(Width & 0x03);
+  if ((!MmioOperation) && (Width == EfiCpuIoWidthUint64)) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  //
+  // Check to see if Address is aligned
+  //
+  if ((Address & (UINT64)(mInStride[Width] - 1)) != 0) {
+    return EFI_UNSUPPORTED;
+  }
+
+  //
+  // Check to see if any address associated with this transfer exceeds the maximum
+  // allowed address.  The maximum address implied by the parameters passed in is
+  // Address + Size * Count.  If the following condition is met, then the transfer
+  // is not supported.
+  //
+  //    Address + Size * Count > (MmioOperation ? MAX_ADDRESS : MAX_IO_PORT_ADDRESS) + 1
+  //
+  // Since MAX_ADDRESS can be the maximum integer value supported by the CPU and Count
+  // can also be the maximum integer value supported by the CPU, this range
+  // check must be adjusted to avoid all overflow conditions.
+  //
+  // The following form of the range check is equivalent but assumes that
+  // MAX_ADDRESS and MAX_IO_PORT_ADDRESS are of the form (2^n - 1).
+  //
+  Limit = (MmioOperation ? MAX_ADDRESS : MAX_IO_PORT_ADDRESS);
+  if (Count == 0) {
+    if (Address > Limit) {
+      return EFI_UNSUPPORTED;
+    }
+  } else {
+    MaxCount = RShiftU64 (Limit, Width);
+    if (MaxCount < (Count - 1)) {
+      return EFI_UNSUPPORTED;
+    }
+
+    if (Address > LShiftU64 (MaxCount - Count + 1, Width)) {
+      return EFI_UNSUPPORTED;
+    }
+  }
+
+  //
+  // Check to see if Buffer is aligned
+  //
+  if (((UINTN)Buffer & ((MIN (sizeof (UINTN), mInStride[Width])  - 1))) != 0) {
+    return EFI_UNSUPPORTED;
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Reads memory-mapped registers.
+
+  The I/O operations are carried out exactly as requested. The caller is responsible
+  for satisfying any alignment and I/O width restrictions that a PI System on a
+  platform might require. For example on some platforms, width requests of
+  EfiCpuIoWidthUint64 do not work. Misaligned buffers, on the other hand, will
+  be handled by the driver.
+
+  If Width is EfiCpuIoWidthUint8, EfiCpuIoWidthUint16, EfiCpuIoWidthUint32,
+  or EfiCpuIoWidthUint64, then both Address and Buffer are incremented for
+  each of the Count operations that is performed.
+
+  If Width is EfiCpuIoWidthFifoUint8, EfiCpuIoWidthFifoUint16,
+  EfiCpuIoWidthFifoUint32, or EfiCpuIoWidthFifoUint64, then only Buffer is
+  incremented for each of the Count operations that is performed. The read or
+  write operation is performed Count times on the same Address.
+
+  If Width is EfiCpuIoWidthFillUint8, EfiCpuIoWidthFillUint16,
+  EfiCpuIoWidthFillUint32, or EfiCpuIoWidthFillUint64, then only Address is
+  incremented for each of the Count operations that is performed. The read or
+  write operation is performed Count times from the first element of Buffer.
+
+  @param[in]  This     A pointer to the EFI_CPU_IO2_PROTOCOL instance.
+  @param[in]  Width    Signifies the width of the I/O or Memory operation.
+  @param[in]  Address  The base address of the I/O operation.
+  @param[in]  Count    The number of I/O operations to perform. The number of
+                       bytes moved is Width size * Count, starting at Address.
+  @param[out] Buffer   For read operations, the destination buffer to store the results.
+                       For write operations, the source buffer from which to write data.
+
+  @retval EFI_SUCCESS            The data was read from or written to the PI system.
+  @retval EFI_INVALID_PARAMETER  Width is invalid for this PI system.
+  @retval EFI_INVALID_PARAMETER  Buffer is NULL.
+  @retval EFI_UNSUPPORTED        The Buffer is not aligned for the given Width.
+  @retval EFI_UNSUPPORTED        The address range specified by Address, Width,
+                                 and Count is not valid for this PI system.
+**/
+EFI_STATUS
+EFIAPI
+CpuMemoryServiceRead (
+  IN  EFI_CPU_IO2_PROTOCOL       *This,
+  IN  EFI_CPU_IO_PROTOCOL_WIDTH  Width,
+  IN  UINT64                     Address,
+  IN  UINTN                      Count,
+  OUT VOID                       *Buffer
+  )
+{
+  EFI_STATUS                 Status;
+  UINT8                      InStride;
+  UINT8                      OutStride;
+  EFI_CPU_IO_PROTOCOL_WIDTH  OperationWidth;
+  UINT8                      *Uint8Buffer;
+
+  Status = CpuIoCheckParameter (TRUE, Width, Address, Count, Buffer);
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  //
+  // Select loop based on the width of the transfer
+  //
+  InStride       = mInStride[Width];
+  OutStride      = mOutStride[Width];
+  OperationWidth = (EFI_CPU_IO_PROTOCOL_WIDTH)(Width & 0x03);
+
+  for (Uint8Buffer = Buffer; Count > 0; Address += InStride, Uint8Buffer += OutStride, Count--) {
+    if (OperationWidth == EfiCpuIoWidthUint8) {
+      *Uint8Buffer = MmioRead8 ((UINTN)Address);
+    } else if (OperationWidth == EfiCpuIoWidthUint16) {
+      *((UINT16 *)Uint8Buffer) = MmioRead16 ((UINTN)Address);
+    } else if (OperationWidth == EfiCpuIoWidthUint32) {
+      *((UINT32 *)Uint8Buffer) = MmioRead32 ((UINTN)Address);
+    } else if (OperationWidth == EfiCpuIoWidthUint64) {
+      *((UINT64 *)Uint8Buffer) = MmioRead64 ((UINTN)Address);
+    }
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Writes memory-mapped registers.
+
+  The I/O operations are carried out exactly as requested. The caller is responsible
+  for satisfying any alignment and I/O width restrictions that a PI System on a
+  platform might require. For example on some platforms, width requests of
+  EfiCpuIoWidthUint64 do not work. Misaligned buffers, on the other hand, will
+  be handled by the driver.
+
+  If Width is EfiCpuIoWidthUint8, EfiCpuIoWidthUint16, EfiCpuIoWidthUint32,
+  or EfiCpuIoWidthUint64, then both Address and Buffer are incremented for
+  each of the Count operations that is performed.
+
+  If Width is EfiCpuIoWidthFifoUint8, EfiCpuIoWidthFifoUint16,
+  EfiCpuIoWidthFifoUint32, or EfiCpuIoWidthFifoUint64, then only Buffer is
+  incremented for each of the Count operations that is performed. The read or
+  write operation is performed Count times on the same Address.
+
+  If Width is EfiCpuIoWidthFillUint8, EfiCpuIoWidthFillUint16,
+  EfiCpuIoWidthFillUint32, or EfiCpuIoWidthFillUint64, then only Address is
+  incremented for each of the Count operations that is performed. The read or
+  write operation is performed Count times from the first element of Buffer.
+
+  @param[in]  This     A pointer to the EFI_CPU_IO2_PROTOCOL instance.
+  @param[in]  Width    Signifies the width of the I/O or Memory operation.
+  @param[in]  Address  The base address of the I/O operation.
+  @param[in]  Count    The number of I/O operations to perform. The number of
+                       bytes moved is Width size * Count, starting at Address.
+  @param[in]  Buffer   For read operations, the destination buffer to store the results.
+                       For write operations, the source buffer from which to write data.
+
+  @retval EFI_SUCCESS            The data was read from or written to the PI system.
+  @retval EFI_INVALID_PARAMETER  Width is invalid for this PI system.
+  @retval EFI_INVALID_PARAMETER  Buffer is NULL.
+  @retval EFI_UNSUPPORTED        The Buffer is not aligned for the given Width.
+  @retval EFI_UNSUPPORTED        The address range specified by Address, Width,
+                                 and Count is not valid for this PI system.
+**/
+EFI_STATUS
+EFIAPI
+CpuMemoryServiceWrite (
+  IN EFI_CPU_IO2_PROTOCOL       *This,
+  IN EFI_CPU_IO_PROTOCOL_WIDTH  Width,
+  IN UINT64                     Address,
+  IN UINTN                      Count,
+  IN VOID                       *Buffer
+  )
+{
+  EFI_STATUS                 Status;
+  UINT8                      InStride;
+  UINT8                      OutStride;
+  EFI_CPU_IO_PROTOCOL_WIDTH  OperationWidth;
+  UINT8                      *Uint8Buffer;
+
+  Status = CpuIoCheckParameter (TRUE, Width, Address, Count, Buffer);
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  //
+  // Select loop based on the width of the transfer
+  //
+  InStride       = mInStride[Width];
+  OutStride      = mOutStride[Width];
+  OperationWidth = (EFI_CPU_IO_PROTOCOL_WIDTH)(Width & 0x03);
+
+  for (Uint8Buffer = Buffer; Count > 0; Address += InStride, Uint8Buffer += OutStride, Count--) {
+    if (OperationWidth == EfiCpuIoWidthUint8) {
+      MmioWrite8 ((UINTN)Address, *Uint8Buffer);
+    } else if (OperationWidth == EfiCpuIoWidthUint16) {
+      MmioWrite16 ((UINTN)Address, *((UINT16 *)Uint8Buffer));
+    } else if (OperationWidth == EfiCpuIoWidthUint32) {
+      MmioWrite32 ((UINTN)Address, *((UINT32 *)Uint8Buffer));
+    } else if (OperationWidth == EfiCpuIoWidthUint64) {
+      MmioWrite64 ((UINTN)Address, *((UINT64 *)Uint8Buffer));
+    }
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Reads I/O registers.
+
+  The I/O operations are carried out exactly as requested. The caller is responsible
+  for satisfying any alignment and I/O width restrictions that a PI System on a
+  platform might require. For example on some platforms, width requests of
+  EfiCpuIoWidthUint64 do not work. Misaligned buffers, on the other hand, will
+  be handled by the driver.
+
+  If Width is EfiCpuIoWidthUint8, EfiCpuIoWidthUint16, EfiCpuIoWidthUint32,
+  or EfiCpuIoWidthUint64, then both Address and Buffer are incremented for
+  each of the Count operations that is performed.
+
+  If Width is EfiCpuIoWidthFifoUint8, EfiCpuIoWidthFifoUint16,
+  EfiCpuIoWidthFifoUint32, or EfiCpuIoWidthFifoUint64, then only Buffer is
+  incremented for each of the Count operations that is performed. The read or
+  write operation is performed Count times on the same Address.
+
+  If Width is EfiCpuIoWidthFillUint8, EfiCpuIoWidthFillUint16,
+  EfiCpuIoWidthFillUint32, or EfiCpuIoWidthFillUint64, then only Address is
+  incremented for each of the Count operations that is performed. The read or
+  write operation is performed Count times from the first element of Buffer.
+
+  @param[in]  This     A pointer to the EFI_CPU_IO2_PROTOCOL instance.
+  @param[in]  Width    Signifies the width of the I/O or Memory operation.
+  @param[in]  Address  The base address of the I/O operation.
+  @param[in]  Count    The number of I/O operations to perform. The number of
+                       bytes moved is Width size * Count, starting at Address.
+  @param[out] Buffer   For read operations, the destination buffer to store the results.
+                       For write operations, the source buffer from which to write data.
+
+  @retval EFI_SUCCESS            The data was read from or written to the PI system.
+  @retval EFI_INVALID_PARAMETER  Width is invalid for this PI system.
+  @retval EFI_INVALID_PARAMETER  Buffer is NULL.
+  @retval EFI_UNSUPPORTED        The Buffer is not aligned for the given Width.
+  @retval EFI_UNSUPPORTED        The address range specified by Address, Width,
+                                 and Count is not valid for this PI system.
+**/
+EFI_STATUS
+EFIAPI
+CpuIoServiceRead (
+  IN  EFI_CPU_IO2_PROTOCOL       *This,
+  IN  EFI_CPU_IO_PROTOCOL_WIDTH  Width,
+  IN  UINT64                     Address,
+  IN  UINTN                      Count,
+  OUT VOID                       *Buffer
+  )
+{
+  EFI_STATUS                 Status;
+  UINT8                      InStride;
+  UINT8                      OutStride;
+  EFI_CPU_IO_PROTOCOL_WIDTH  OperationWidth;
+  UINT8                      *Uint8Buffer;
+
+  Status = CpuIoCheckParameter (FALSE, Width, Address, Count, Buffer);
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  Address += PcdGet64 (PcdPciIoTranslation);
+
+  //
+  // Select loop based on the width of the transfer
+  //
+  InStride       = mInStride[Width];
+  OutStride      = mOutStride[Width];
+  OperationWidth = (EFI_CPU_IO_PROTOCOL_WIDTH)(Width & 0x03);
+
+  for (Uint8Buffer = Buffer; Count > 0; Address += InStride, Uint8Buffer += OutStride, Count--) {
+    if (OperationWidth == EfiCpuIoWidthUint8) {
+      *Uint8Buffer = MmioRead8 ((UINTN)Address);
+    } else if (OperationWidth == EfiCpuIoWidthUint16) {
+      *((UINT16 *)Uint8Buffer) = MmioRead16 ((UINTN)Address);
+    } else if (OperationWidth == EfiCpuIoWidthUint32) {
+      *((UINT32 *)Uint8Buffer) = MmioRead32 ((UINTN)Address);
+    }
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Write I/O registers.
+
+  The I/O operations are carried out exactly as requested. The caller is responsible
+  for satisfying any alignment and I/O width restrictions that a PI System on a
+  platform might require. For example on some platforms, width requests of
+  EfiCpuIoWidthUint64 do not work. Misaligned buffers, on the other hand, will
+  be handled by the driver.
+
+  If Width is EfiCpuIoWidthUint8, EfiCpuIoWidthUint16, EfiCpuIoWidthUint32,
+  or EfiCpuIoWidthUint64, then both Address and Buffer are incremented for
+  each of the Count operations that is performed.
+
+  If Width is EfiCpuIoWidthFifoUint8, EfiCpuIoWidthFifoUint16,
+  EfiCpuIoWidthFifoUint32, or EfiCpuIoWidthFifoUint64, then only Buffer is
+  incremented for each of the Count operations that is performed. The read or
+  write operation is performed Count times on the same Address.
+
+  If Width is EfiCpuIoWidthFillUint8, EfiCpuIoWidthFillUint16,
+  EfiCpuIoWidthFillUint32, or EfiCpuIoWidthFillUint64, then only Address is
+  incremented for each of the Count operations that is performed. The read or
+  write operation is performed Count times from the first element of Buffer.
+
+  @param[in]  This     A pointer to the EFI_CPU_IO2_PROTOCOL instance.
+  @param[in]  Width    Signifies the width of the I/O or Memory operation.
+  @param[in]  Address  The base address of the I/O operation.
+  @param[in]  Count    The number of I/O operations to perform. The number of
+                       bytes moved is Width size * Count, starting at Address.
+  @param[in]  Buffer   For read operations, the destination buffer to store the results.
+                       For write operations, the source buffer from which to write data.
+
+  @retval EFI_SUCCESS            The data was read from or written to the PI system.
+  @retval EFI_INVALID_PARAMETER  Width is invalid for this PI system.
+  @retval EFI_INVALID_PARAMETER  Buffer is NULL.
+  @retval EFI_UNSUPPORTED        The Buffer is not aligned for the given Width.
+  @retval EFI_UNSUPPORTED        The address range specified by Address, Width,
+                                 and Count is not valid for this PI system.
+**/
+EFI_STATUS
+EFIAPI
+CpuIoServiceWrite (
+  IN EFI_CPU_IO2_PROTOCOL       *This,
+  IN EFI_CPU_IO_PROTOCOL_WIDTH  Width,
+  IN UINT64                     Address,
+  IN UINTN                      Count,
+  IN VOID                       *Buffer
+  )
+{
+  EFI_STATUS                 Status;
+  UINT8                      InStride;
+  UINT8                      OutStride;
+  EFI_CPU_IO_PROTOCOL_WIDTH  OperationWidth;
+  UINT8                      *Uint8Buffer;
+
+  //
+  // Make sure the parameters are valid
+  //
+  Status = CpuIoCheckParameter (FALSE, Width, Address, Count, Buffer);
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  Address += PcdGet64 (PcdPciIoTranslation);
+
+  //
+  // Select loop based on the width of the transfer
+  //
+  InStride       = mInStride[Width];
+  OutStride      = mOutStride[Width];
+  OperationWidth = (EFI_CPU_IO_PROTOCOL_WIDTH)(Width & 0x03);
+
+  for (Uint8Buffer = (UINT8 *)Buffer; Count > 0; Address += InStride, Uint8Buffer += OutStride, Count--) {
+    if (OperationWidth == EfiCpuIoWidthUint8) {
+      MmioWrite8 ((UINTN)Address, *Uint8Buffer);
+    } else if (OperationWidth == EfiCpuIoWidthUint16) {
+      MmioWrite16 ((UINTN)Address, *((UINT16 *)Uint8Buffer));
+    } else if (OperationWidth == EfiCpuIoWidthUint32) {
+      MmioWrite32 ((UINTN)Address, *((UINT32 *)Uint8Buffer));
+    }
+  }
+
+  return EFI_SUCCESS;
+}
+
+//
+// CPU I/O 2 Protocol instance
+//
+STATIC EFI_CPU_IO2_PROTOCOL  mCpuIo2 = {
+  {
+    CpuMemoryServiceRead,
+    CpuMemoryServiceWrite
+  },
+  {
+    CpuIoServiceRead,
+    CpuIoServiceWrite
+  }
+};
+
+/**
+  The user Entry Point for module CpuIo2Dxe. The user code starts with this function.
+
+  @param[in] ImageHandle    The firmware allocated handle for the EFI image.
+  @param[in] SystemTable    A pointer to the EFI System Table.
+
+  @retval EFI_SUCCESS       The entry point is executed successfully.
+  @retval other             Some error occurs when executing this entry point.
+**/
+EFI_STATUS
+EFIAPI
+PciCpuIo2Initialize (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  )
+{
+  EFI_STATUS  Status;
+
+  ASSERT_PROTOCOL_ALREADY_INSTALLED (NULL, &gEfiCpuIo2ProtocolGuid);
+  Status = gBS->InstallMultipleProtocolInterfaces (
+                  &mHandle,
+                  &gEfiCpuIo2ProtocolGuid,
+                  &mCpuIo2,
+                  NULL
+                  );
+  ASSERT_EFI_ERROR (Status);
+  return Status;
+}
diff --git a/OvmfPkg/LoongArchVirt/Drivers/PciCpuIo2Dxe/PciCpuIo2Dxe.inf b/OvmfPkg/LoongArchVirt/Drivers/PciCpuIo2Dxe/PciCpuIo2Dxe.inf
new file mode 100644
index 0000000000..bee546b5d8
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Drivers/PciCpuIo2Dxe/PciCpuIo2Dxe.inf
@@ -0,0 +1,45 @@
+## @file
+#  Produces the CPU I/O 2 Protocol by using the services of the I/O Library.
+#
+#  Copyright (c) 2009 - 2014, Intel Corporation. All rights reserved.<BR>
+#  Copyright (c) 2016, Linaro Ltd. All rights reserved.<BR>
+#  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = PciCpuIo2Dxe
+  FILE_GUID                      = 66017724-E5F7-F983-9EC5-8934866AA676
+  MODULE_TYPE                    = DXE_DRIVER
+  VERSION_STRING                 = 1.0
+  ENTRY_POINT                    = PciCpuIo2Initialize
+
+#
+#  VALID_ARCHITECTURES           = LOONGARCH64
+#
+
+[Sources]
+  PciCpuIo2Dxe.c
+
+[Packages]
+  MdePkg/MdePkg.dec
+
+[LibraryClasses]
+  UefiDriverEntryPoint
+  BaseLib
+  DebugLib
+  IoLib
+  PcdLib
+  UefiBootServicesTableLib
+
+[Pcd]
+  gEfiMdePkgTokenSpaceGuid.PcdPciIoTranslation
+
+[Protocols]
+  gEfiCpuIo2ProtocolGuid                         ## PRODUCES
+
+[Depex]
+  TRUE
-- 
2.27.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#110531): https://edk2.groups.io/g/devel/message/110531
Mute This Topic: https://groups.io/mt/102342175/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* [edk2-devel] [PATCH v1 18/29] OvmfPkg/LoongArchVirt: Add stable timer driver
       [not found] <20231102134249.3983594-1-lichao@loongson.cn>
                   ` (9 preceding siblings ...)
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 17/29] OvmfPkg/LoongArchVirt: Add PciCpuIo2Dxe module Chao Li
@ 2023-11-02 13:42 ` Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 19/29] OvmfPkg/LoongArchVirt: Add a NULL library named CollectApResouceLibNull Chao Li
                   ` (6 subsequent siblings)
  17 siblings, 0 replies; 18+ messages in thread
From: Chao Li @ 2023-11-02 13:42 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Jiewen Yao, Jordan Justen, Gerd Hoffmann,
	Baoqi Zhang

Add a CPU timer driver named StableTimerDxe, which proviedes
EFI_TIMER_ARCH_PROTOCOL for LoongArch.

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

Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Chao Li <lichao@loongson.cn>
Co-authored-by: Baoqi Zhang <zhangbaoqi@loongson.cn>
---
 .../Drivers/StableTimerDxe/Timer.c            | 381 ++++++++++++++++++
 .../Drivers/StableTimerDxe/Timer.h            | 127 ++++++
 .../Drivers/StableTimerDxe/TimerDxe.inf       |  41 ++
 3 files changed, 549 insertions(+)
 create mode 100644 OvmfPkg/LoongArchVirt/Drivers/StableTimerDxe/Timer.c
 create mode 100644 OvmfPkg/LoongArchVirt/Drivers/StableTimerDxe/Timer.h
 create mode 100644 OvmfPkg/LoongArchVirt/Drivers/StableTimerDxe/TimerDxe.inf

diff --git a/OvmfPkg/LoongArchVirt/Drivers/StableTimerDxe/Timer.c b/OvmfPkg/LoongArchVirt/Drivers/StableTimerDxe/Timer.c
new file mode 100644
index 0000000000..9f0feaa786
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Drivers/StableTimerDxe/Timer.c
@@ -0,0 +1,381 @@
+/** @file
+  Timer Architectural Protocol as defined in the DXE CIS
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Protocol/Cpu.h>
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/TimerLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Register/LoongArch64/Csr.h>
+#include "Timer.h"
+
+//
+// The handle onto which the Timer Architectural Protocol will be installed
+//
+EFI_HANDLE  mTimerHandle             = NULL;
+EFI_EVENT   EfiExitBootServicesEvent = (EFI_EVENT)NULL;
+
+//
+// The Timer Architectural Protocol that this driver produces
+//
+EFI_TIMER_ARCH_PROTOCOL  mTimer = {
+  TimerDriverRegisterHandler,
+  TimerDriverSetTimerPeriod,
+  TimerDriverGetTimerPeriod,
+  TimerDriverGenerateSoftInterrupt
+};
+
+//
+// Pointer to the CPU Architectural Protocol instance
+//
+EFI_CPU_ARCH_PROTOCOL  *mCpu;
+
+//
+// The notification function to call on every timer interrupt.
+// A bug in the compiler prevents us from initializing this here.
+//
+EFI_TIMER_NOTIFY  mTimerNotifyFunction;
+
+/**
+  Sets the counter value for timer.
+
+  @param Count    The 16-bit counter value to program into stable timer.
+
+  @retval VOID
+**/
+VOID
+SetPitCount (
+  IN UINT64  Count
+  )
+{
+  if (Count <= 4) {
+    return;
+  }
+
+  Count &= LOONGARCH_CSR_TMCFG_TIMEVAL;
+  Count |= LOONGARCH_CSR_TMCFG_EN | LOONGARCH_CSR_TMCFG_PERIOD;
+  CsrWrite (LOONGARCH_CSR_TMCFG, Count);
+}
+
+/**
+  Timer Interrupt Handler.
+
+  @param InterruptType    The type of interrupt that occurred
+  @param SystemContext    A pointer to the system context when the interrupt occurred
+
+  @retval VOID
+**/
+VOID
+EFIAPI
+TimerInterruptHandler (
+  IN EFI_EXCEPTION_TYPE  InterruptType,
+  IN EFI_SYSTEM_CONTEXT  SystemContext
+  )
+{
+  EFI_TPL  OriginalTPL;
+
+  OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL);
+
+  //
+  // Clear interrupt.
+  //
+  CsrWrite (LOONGARCH_CSR_TINTCLR, 0x1);
+
+  if (mTimerNotifyFunction != NULL) {
+    //
+    // @bug : This does not handle missed timer interrupts
+    //
+    mTimerNotifyFunction (mTimerPeriod);
+  }
+
+  gBS->RestoreTPL (OriginalTPL);
+}
+
+/**
+  This function registers the handler NotifyFunction so it is called every time
+  the timer interrupt fires.  It also passes the amount of time since the last
+  handler call to the NotifyFunction.  If NotifyFunction is NULL, then the
+  handler is unregistered.  If the handler is registered, then EFI_SUCCESS is
+  returned.  If the CPU does not support registering a timer interrupt handler,
+  then EFI_UNSUPPORTED is returned.  If an attempt is made to register a handler
+  when a handler is already registered, then EFI_ALREADY_STARTED is returned.
+  If an attempt is made to unregister a handler when a handler is not registered,
+  then EFI_INVALID_PARAMETER is returned.  If an error occurs attempting to
+  register the NotifyFunction with the timer interrupt, then EFI_DEVICE_ERROR
+  is returned.
+
+  @param This             The EFI_TIMER_ARCH_PROTOCOL instance.
+  @param NotifyFunction   The function to call when a timer interrupt fires.  This
+                          function executes at TPL_HIGH_LEVEL.  The DXE Core will
+                          register a handler for the timer interrupt, so it can know
+                          how much time has passed.  This information is used to
+                          signal timer based events.  NULL will unregister the handler.
+
+  @retval        EFI_SUCCESS            The timer handler was registered.
+  @retval        EFI_UNSUPPORTED        The platform does not support timer interrupts.
+  @retval        EFI_ALREADY_STARTED    NotifyFunction is not NULL, and a handler is already
+                                        registered.
+  @retval        EFI_INVALID_PARAMETER  NotifyFunction is NULL, and a handler was not
+                                        previously registered.
+  @retval        EFI_DEVICE_ERROR       The timer handler could not be registered.
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverRegisterHandler (
+  IN EFI_TIMER_ARCH_PROTOCOL  *This,
+  IN EFI_TIMER_NOTIFY         NotifyFunction
+  )
+{
+  //
+  // Check for invalid parameters
+  //
+  if ((NotifyFunction == NULL) && (mTimerNotifyFunction == NULL)) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  if ((NotifyFunction != NULL) && (mTimerNotifyFunction != NULL)) {
+    return EFI_ALREADY_STARTED;
+  }
+
+  mTimerNotifyFunction = NotifyFunction;
+
+  return EFI_SUCCESS;
+}
+
+/**
+  This function adjusts the period of timer interrupts to the value specified
+  by TimerPeriod.  If the timer period is updated, then the selected timer
+  period is stored in EFI_TIMER.TimerPeriod, and EFI_SUCCESS is returned.  If
+  the timer hardware is not programmable, then EFI_UNSUPPORTED is returned.
+  If an error occurs while attempting to update the timer period, then the
+  timer hardware will be put back in its state prior to this call, and
+  EFI_DEVICE_ERROR is returned.  If TimerPeriod is 0, then the timer interrupt
+  is disabled.  This is not the same as disabling the CPU's interrupts.
+  Instead, it must either turn off the timer hardware, or it must adjust the
+  interrupt controller so that a CPU interrupt is not generated when the timer
+  interrupt fires.
+
+  @param This            The EFI_TIMER_ARCH_PROTOCOL instance.
+  @param TimerPeriod     The rate to program the timer interrupt in 100 nS units.  If
+                         the timer hardware is not programmable, then EFI_UNSUPPORTED is
+                         returned.  If the timer is programmable, then the timer period
+                         will be rounded up to the nearest timer period that is supported
+                         by the timer hardware.  If TimerPeriod is set to 0, then the
+                         timer interrupts will be disabled.
+
+  @retval        EFI_SUCCESS       The timer period was changed.
+  @retval        EFI_UNSUPPORTED   The platform cannot change the period of the timer interrupt.
+  @retval        EFI_DEVICE_ERROR  The timer period could not be changed due to a device error.
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverSetTimerPeriod (
+  IN EFI_TIMER_ARCH_PROTOCOL  *This,
+  IN UINT64                   TimerPeriod
+  )
+{
+  UINT64  TimerCount;
+
+  if (TimerPeriod == 0) {
+    //
+    // Disable timer interrupt for a TimerPeriod of 0
+    //
+    mCpu->DisableInterrupt (mCpu);
+  } else {
+    TimerCount = TimerPeriod * GetPerformanceCounterProperties (NULL, NULL) / 10000000ULL;
+
+    if (TimerCount >= BIT48) {
+      TimerCount = 0;
+    }
+
+    //
+    // Program the stable timer with the new count value
+    //
+    mTimerTicks = TimerCount;
+    SetPitCount (TimerCount);
+
+    //
+    // Enable timer interrupt
+    //
+    mCpu->EnableInterrupt (mCpu);
+  }
+
+  //
+  // Save the new timer period
+  //
+  mTimerPeriod = TimerPeriod;
+
+  return EFI_SUCCESS;
+}
+
+/**
+  This function retrieves the period of timer interrupts in 100 ns units,
+  returns that value in TimerPeriod, and returns EFI_SUCCESS.  If TimerPeriod
+  is NULL, then EFI_INVALID_PARAMETER is returned.  If a TimerPeriod of 0 is
+  returned, then the timer is currently disabled.
+
+  @param This            The EFI_TIMER_ARCH_PROTOCOL instance.
+  @param TimerPeriod     A pointer to the timer period to retrieve in 100 ns units.  If
+                         0 is returned, then the timer is currently disabled.
+
+  @retval EFI_SUCCESS            The timer period was returned in TimerPeriod.
+  @retval EFI_INVALID_PARAMETER  TimerPeriod is NULL.
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverGetTimerPeriod (
+  IN EFI_TIMER_ARCH_PROTOCOL  *This,
+  OUT UINT64                  *TimerPeriod
+  )
+{
+  if (TimerPeriod == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  *TimerPeriod = mTimerPeriod;
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Disable the timer
+  DXE Core will disable the timer after all the event handlers have run.
+
+  @param[in]  Event   The Event that is being processed
+  @param[in]  Context Event Context
+**/
+VOID
+EFIAPI
+ExitBootServicesEvent (
+  IN EFI_EVENT  Event,
+  IN VOID       *Context
+  )
+{
+  /*
+   * Disable timer interrupt when exiting boot service
+   */
+  CsrWrite (LOONGARCH_CSR_TMCFG, 0x0);
+}
+
+/**
+  This function generates a soft timer interrupt. If the platform does not support soft
+  timer interrupts, then EFI_UNSUPPORTED is returned. Otherwise, EFI_SUCCESS is returned.
+  If a handler has been registered through the EFI_TIMER_ARCH_PROTOCOL.RegisterHandler ()
+  service, then a soft timer interrupt will be generated. If the timer interrupt is
+  enabled when this service is called, then the registered handler will be invoked. The
+  registered handler should not be able to distinguish a hardware-generated timer
+  interrupt from a software-generated timer interrupt.
+
+  @param This              The EFI_TIMER_ARCH_PROTOCOL instance.
+
+  @retval EFI_SUCCESS       The soft timer interrupt was generated.
+  @retval EFI_UNSUPPORTED   The platform does not support the generation of soft timer interrupts.
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverGenerateSoftInterrupt (
+  IN EFI_TIMER_ARCH_PROTOCOL  *This
+  )
+{
+  return EFI_UNSUPPORTED;
+}
+
+/**
+  Initialize the Timer Architectural Protocol driver
+
+  @param ImageHandle     ImageHandle of the loaded driver
+  @param SystemTable     Pointer to the System Table
+
+  @retval EFI_SUCCESS            Timer Architectural Protocol created
+  @retval EFI_OUT_OF_RESOURCES   Not enough resources available to initialize driver.
+  @retval EFI_DEVICE_ERROR       A device error occurred attempting to initialize the driver.
+**/
+EFI_STATUS
+EFIAPI
+StableTimerDriverInitialize (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  )
+{
+  EFI_STATUS  Status;
+  UINT32      TimerVector;
+
+  //
+  // Initialize the pointer to our notify function.
+  //
+  mTimerNotifyFunction = NULL;
+
+  //
+  // Make sure the Timer Architectural Protocol is not already installed in the system
+  //
+  ASSERT_PROTOCOL_ALREADY_INSTALLED (NULL, &gEfiTimerArchProtocolGuid);
+
+  //
+  // Find the CPU architectural protocol.
+  //
+  Status = gBS->LocateProtocol (&gEfiCpuArchProtocolGuid, NULL, (VOID **)&mCpu);
+  ASSERT_EFI_ERROR (Status);
+
+  //
+  // Force the timer to be disabled
+  //
+  Status = TimerDriverSetTimerPeriod (&mTimer, 0);
+  ASSERT_EFI_ERROR (Status);
+
+  //
+  // Calculate const frequence
+  //
+  DEBUG ((
+    DEBUG_INFO,
+    "===========Stable timer freq %d Hz=============\n",
+    GetPerformanceCounterProperties (NULL, NULL)
+    ));
+
+  //
+  // Install interrupt handler for Stable Timer #0 (ISA IRQ0)
+  //
+  TimerVector = EXCEPT_LOONGARCH_INT_TIMER;
+  Status      = mCpu->RegisterInterruptHandler (mCpu, TimerVector, TimerInterruptHandler);
+  ASSERT_EFI_ERROR (Status);
+
+  //
+  // Enable TI local timer interrupt
+  //
+  EnableLocalInterrupts (1 << EXCEPT_LOONGARCH_INT_TIMER);
+
+  //
+  // Force the timer to be enabled at its default period
+  //
+  Status = TimerDriverSetTimerPeriod (&mTimer, DEFAULT_TIMER_TICK_DURATION);
+  ASSERT_EFI_ERROR (Status);
+
+  //
+  // Install the Timer Architectural Protocol onto a new handle
+  //
+  Status = gBS->InstallMultipleProtocolInterfaces (
+                  &mTimerHandle,
+                  &gEfiTimerArchProtocolGuid,
+                  &mTimer,
+                  NULL
+                  );
+
+  ASSERT_EFI_ERROR (Status);
+
+  // Register for an ExitBootServicesEvent
+  Status = gBS->CreateEvent (
+                  EVT_SIGNAL_EXIT_BOOT_SERVICES,
+                  TPL_NOTIFY,
+                  ExitBootServicesEvent,
+                  NULL,
+                  &EfiExitBootServicesEvent
+                  );
+  ASSERT_EFI_ERROR (Status);
+
+  return Status;
+}
diff --git a/OvmfPkg/LoongArchVirt/Drivers/StableTimerDxe/Timer.h b/OvmfPkg/LoongArchVirt/Drivers/StableTimerDxe/Timer.h
new file mode 100644
index 0000000000..12a59af1ed
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Drivers/StableTimerDxe/Timer.h
@@ -0,0 +1,127 @@
+/** @file
+  Private data structures
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef TIMER_H_
+#define TIMER_H_
+
+#include <Protocol/Timer.h>
+
+#define DEFAULT_TIMER_TICK_DURATION  100000 // 10ms = 100000 100 ns units
+
+//
+// The current period of the timer interrupt
+//
+volatile UINT64  mTimerPeriod = 0;
+volatile UINT64  mTimerTicks  = 0;
+
+/**
+  This function adjusts the period of timer interrupts to the value specified
+  by TimerPeriod.  If the timer period is updated, then the selected timer
+  period is stored in EFI_TIMER.TimerPeriod, and EFI_SUCCESS is returned.  If
+  the timer hardware is not programmable, then EFI_UNSUPPORTED is returned.
+  If an error occurs while attempting to update the timer period, then the
+  timer hardware will be put back in its state prior to this call, and
+  EFI_DEVICE_ERROR is returned.  If TimerPeriod is 0, then the timer interrupt
+  is disabled.  This is not the same as disabling the CPU's interrupts.
+  Instead, it must either turn off the timer hardware, or it must adjust the
+  interrupt controller so that a CPU interrupt is not generated when the timer
+  interrupt fires.
+
+  @param This            The EFI_TIMER_ARCH_PROTOCOL instance.
+  @param NotifyFunction  The rate to program the timer interrupt in 100 nS units.  If
+                         the timer hardware is not programmable, then EFI_UNSUPPORTED is
+                         returned.  If the timer is programmable, then the timer period
+                         will be rounded up to the nearest timer period that is supported
+                         by the timer hardware.  If TimerPeriod is set to 0, then the
+                         timer interrupts will be disabled.
+
+  @retval        EFI_SUCCESS       The timer period was changed.
+  @retval        EFI_UNSUPPORTED   The platform cannot change the period of the timer interrupt.
+  @retval        EFI_DEVICE_ERROR  The timer period could not be changed due to a device error.
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverRegisterHandler (
+  IN EFI_TIMER_ARCH_PROTOCOL  *This,
+  IN EFI_TIMER_NOTIFY         NotifyFunction
+  );
+
+/**
+  This function adjusts the period of timer interrupts to the value specified
+  by TimerPeriod.  If the timer period is updated, then the selected timer
+  period is stored in EFI_TIMER.TimerPeriod, and EFI_SUCCESS is returned.  If
+  the timer hardware is not programmable, then EFI_UNSUPPORTED is returned.
+  If an error occurs while attempting to update the timer period, then the
+  timer hardware will be put back in its state prior to this call, and
+  EFI_DEVICE_ERROR is returned.  If TimerPeriod is 0, then the timer interrupt
+  is disabled.  This is not the same as disabling the CPU's interrupts.
+  Instead, it must either turn off the timer hardware, or it must adjust the
+  interrupt controller so that a CPU interrupt is not generated when the timer
+  interrupt fires.
+
+  @param This            The EFI_TIMER_ARCH_PROTOCOL instance.
+  @param TimerPeriod     The rate to program the timer interrupt in 100 nS units.  If
+                         the timer hardware is not programmable, then EFI_UNSUPPORTED is
+                         returned.  If the timer is programmable, then the timer period
+                         will be rounded up to the nearest timer period that is supported
+                         by the timer hardware.  If TimerPeriod is set to 0, then the
+                         timer interrupts will be disabled.
+
+  @retval        EFI_SUCCESS       The timer period was changed.
+  @retval        EFI_UNSUPPORTED   The platform cannot change the period of the timer interrupt.
+  @retval        EFI_DEVICE_ERROR  The timer period could not be changed due to a device error.
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverSetTimerPeriod (
+  IN EFI_TIMER_ARCH_PROTOCOL  *This,
+  IN UINT64                   TimerPeriod
+  );
+
+/**
+  This function retrieves the period of timer interrupts in 100 ns units,
+  returns that value in TimerPeriod, and returns EFI_SUCCESS.  If TimerPeriod
+  is NULL, then EFI_INVALID_PARAMETER is returned.  If a TimerPeriod of 0 is
+  returned, then the timer is currently disabled.
+
+  @param This            The EFI_TIMER_ARCH_PROTOCOL instance.
+  @param TimerPeriod     A pointer to the timer period to retrieve in 100 ns units.  If
+                         0 is returned, then the timer is currently disabled.
+
+  @retval EFI_SUCCESS            The timer period was returned in TimerPeriod.
+  @retval EFI_INVALID_PARAMETER  TimerPeriod is NULL.
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverGetTimerPeriod (
+  IN EFI_TIMER_ARCH_PROTOCOL  *This,
+  OUT UINT64                  *TimerPeriod
+  );
+
+/**
+  This function generates a soft timer interrupt. If the platform does not support soft
+  timer interrupts, then EFI_UNSUPPORTED is returned. Otherwise, EFI_SUCCESS is returned.
+  If a handler has been registered through the EFI_TIMER_ARCH_PROTOCOL.RegisterHandler()
+  service, then a soft timer interrupt will be generated. If the timer interrupt is
+  enabled when this service is called, then the registered handler will be invoked. The
+  registered handler should not be able to distinguish a hardware-generated timer
+  interrupt from a software-generated timer interrupt.
+
+  @param This              The EFI_TIMER_ARCH_PROTOCOL instance.
+
+  @retval EFI_SUCCESS       The soft timer interrupt was generated.
+  @retval EFI_UNSUPPORTED   The platform does not support the generation of soft timer interrupts.
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverGenerateSoftInterrupt (
+  IN EFI_TIMER_ARCH_PROTOCOL  *This
+  );
+
+#endif // TIMER_H_
diff --git a/OvmfPkg/LoongArchVirt/Drivers/StableTimerDxe/TimerDxe.inf b/OvmfPkg/LoongArchVirt/Drivers/StableTimerDxe/TimerDxe.inf
new file mode 100644
index 0000000000..12c78a4088
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Drivers/StableTimerDxe/TimerDxe.inf
@@ -0,0 +1,41 @@
+## @file
+#  Stable timer driver that provides Timer Arch protocol.
+#
+#  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = Timer
+  MODULE_UNI_FILE                = Timer.uni
+  FILE_GUID                      = AEBE2648-47A9-40FA-83FD-06AA88443BB2
+  MODULE_TYPE                    = DXE_DRIVER
+  VERSION_STRING                 = 1.0
+  ENTRY_POINT                    = StableTimerDriverInitialize
+
+#
+#  VALID_ARCHITECTURES           = LOONGARCH64
+#
+
+[Sources]
+  Timer.c
+
+[Packages]
+  MdePkg/MdePkg.dec
+
+[LibraryClasses]
+  UefiBootServicesTableLib
+  BaseLib
+  DebugLib
+  UefiDriverEntryPoint
+  IoLib
+  TimerLib
+
+[Protocols]
+  gEfiCpuArchProtocolGuid       ## CONSUMES
+  gEfiTimerArchProtocolGuid     ## PRODUCES
+
+[depex]
+  gEfiCpuArchProtocolGuid
-- 
2.27.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#110544): https://edk2.groups.io/g/devel/message/110544
Mute This Topic: https://groups.io/mt/102342337/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* [edk2-devel] [PATCH v1 19/29] OvmfPkg/LoongArchVirt: Add a NULL library named CollectApResouceLibNull
       [not found] <20231102134249.3983594-1-lichao@loongson.cn>
                   ` (10 preceding siblings ...)
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 18/29] OvmfPkg/LoongArchVirt: Add stable timer driver Chao Li
@ 2023-11-02 13:42 ` Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 21/29] OvmfPkg/LoongArchVirt: Add real time clock library Chao Li
                   ` (5 subsequent siblings)
  17 siblings, 0 replies; 18+ messages in thread
From: Chao Li @ 2023-11-02 13:42 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Jiewen Yao, Jordan Justen, Gerd Hoffmann

This Library is used to collect APs resources, but is currently NULL
for OvmfPkg, because it is not used by the LoongArch virtual machine.

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

Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Chao Li <lichao@loongson.cn>
---
 .../CollectApResourceLibNull.c                | 35 +++++++++++++++++++
 .../CollectApResourceLibNull.inf              | 32 +++++++++++++++++
 .../CollectApResourceLibNull.uni              |  9 +++++
 3 files changed, 76 insertions(+)
 create mode 100644 OvmfPkg/LoongArchVirt/Library/CollectApResouceLibNull/CollectApResourceLibNull.c
 create mode 100644 OvmfPkg/LoongArchVirt/Library/CollectApResouceLibNull/CollectApResourceLibNull.inf
 create mode 100644 OvmfPkg/LoongArchVirt/Library/CollectApResouceLibNull/CollectApResourceLibNull.uni

diff --git a/OvmfPkg/LoongArchVirt/Library/CollectApResouceLibNull/CollectApResourceLibNull.c b/OvmfPkg/LoongArchVirt/Library/CollectApResouceLibNull/CollectApResourceLibNull.c
new file mode 100644
index 0000000000..528914973e
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/CollectApResouceLibNull/CollectApResourceLibNull.c
@@ -0,0 +1,35 @@
+/** @file
+  LoongArch64 CPU Collect AP resource NULL Library functions.
+
+  Copyright (c) 2023, Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Library/BaseLib.h>
+#include <Register/LoongArch64/Csr.h>
+#include "../../../UefiCpuPkg/Library/LoongArch64MpInitLib/MpLib.h"
+
+VOID
+SaveProcessorResourceData (
+  IN PROCESSOR_RESOURCE_DATA *
+  );
+
+VOID
+EFIAPI
+SaveProcessorResource (
+  PROCESSOR_RESOURCE_DATA  *mProcessorResource
+  )
+{
+  SaveProcessorResourceData (mProcessorResource);
+}
+
+VOID
+EFIAPI
+CollectAllProcessorResource (
+  VOID
+  )
+{
+  return;
+}
diff --git a/OvmfPkg/LoongArchVirt/Library/CollectApResouceLibNull/CollectApResourceLibNull.inf b/OvmfPkg/LoongArchVirt/Library/CollectApResouceLibNull/CollectApResourceLibNull.inf
new file mode 100644
index 0000000000..d8d281421c
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/CollectApResouceLibNull/CollectApResourceLibNull.inf
@@ -0,0 +1,32 @@
+## @file
+#  LoongArch64 CPU Collect AP resource NULL Library.
+#
+#  Copyright (c) 2023, Loongson Technology Corporation Limited. All rights reserved.<BR>
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = CollectApResourceLibNull
+  MODULE_UNI_FILE                = CollectApResourceLibNull.uni
+  FILE_GUID                      = 8C3B54BF-6A9F-E8B4-4D57-67B3AB578DD6
+  MODULE_TYPE                    = BASE
+  VERSION_STRING                 = 1.1
+  LIBRARY_CLASS                  = BaseLib
+
+[Sources.common]
+  CollectApResourceLibNull.c
+
+[Packages]
+  MdePkg/MdePkg.dec
+  UefiCpuPkg/UefiCpuPkg.dec
+
+[LibraryClasses]
+  BaseLib
+  MemoryAllocationLib
+  HobLib
+  SynchronizationLib
+
+[Pcd]
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber
diff --git a/OvmfPkg/LoongArchVirt/Library/CollectApResouceLibNull/CollectApResourceLibNull.uni b/OvmfPkg/LoongArchVirt/Library/CollectApResouceLibNull/CollectApResourceLibNull.uni
new file mode 100644
index 0000000000..701e2d7e6b
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/CollectApResouceLibNull/CollectApResourceLibNull.uni
@@ -0,0 +1,9 @@
+// @file
+//  LoongArch64 CPU Collect AP resource NULL Library.
+//
+//  Copyright (c) 2023, Loongson Technology Corporation Limited. All rights reserved.<BR>
+//  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+#string STR_MODULE_ABSTRACT             #language en-US "CPU Collect AP resource NULL Library."
+
+#string STR_MODULE_DESCRIPTION          #language en-US "CPU Collect AP resource NULL Library."
-- 
2.27.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#110530): https://edk2.groups.io/g/devel/message/110530
Mute This Topic: https://groups.io/mt/102342170/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* [edk2-devel] [PATCH v1 21/29] OvmfPkg/LoongArchVirt: Add real time clock library
       [not found] <20231102134249.3983594-1-lichao@loongson.cn>
                   ` (11 preceding siblings ...)
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 19/29] OvmfPkg/LoongArchVirt: Add a NULL library named CollectApResouceLibNull Chao Li
@ 2023-11-02 13:42 ` Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 23/29] OvmfPkg/LoongArchVirt: Add PeiServiceTablePointerLib Chao Li
                   ` (4 subsequent siblings)
  17 siblings, 0 replies; 18+ messages in thread
From: Chao Li @ 2023-11-02 13:42 UTC (permalink / raw)
  To: devel
  Cc: Ard Biesheuvel, Jiewen Yao, Jordan Justen, Gerd Hoffmann,
	Baoqi Zhang, Xianglai Li

This library is provides real time clock for LoongArch virtual machine.

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

Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Chao Li <lichao@loongson.cn>
Co-authored-by: Baoqi Zhang <zhangbaoqi@loongson.cn>
Co-authored-by: Xianglai Li <lixianglai@loongson.cn>
---
 .../DxeLsRealTimeClockLib.c                   | 333 ++++++++++++++++++
 .../DxeLsRealTimeClockLib.inf                 |  42 +++
 .../LsRealTimeClockLib/LsRealTimeClock.h      |  47 +++
 .../PeiLsRealTimeClockLib.c                   |  31 ++
 .../PeiLsRealTimeClockLib.inf                 |  29 ++
 5 files changed, 482 insertions(+)
 create mode 100644 OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/DxeLsRealTimeClockLib.c
 create mode 100644 OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/DxeLsRealTimeClockLib.inf
 create mode 100644 OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/LsRealTimeClock.h
 create mode 100644 OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/PeiLsRealTimeClockLib.c
 create mode 100644 OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/PeiLsRealTimeClockLib.inf

diff --git a/OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/DxeLsRealTimeClockLib.c b/OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/DxeLsRealTimeClockLib.c
new file mode 100644
index 0000000000..d634d30fd1
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/DxeLsRealTimeClockLib.c
@@ -0,0 +1,333 @@
+/** @file
+  Implement EFI RealTimeClock runtime services via RTC Lib.
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Uefi.h>
+#include <PiDxe.h>
+
+#include <Guid/EventGroup.h>
+#include <Guid/GlobalVariable.h>
+
+#include <Include/Base.h>
+#include <Library/BaseLib.h>
+#include <Library/HobLib.h>
+#include <Library/DebugLib.h>
+#include <Library/DxeServicesTableLib.h>
+#include <Library/IoLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/PcdLib.h>
+#include <Library/RealTimeClockLib.h>
+#include <Library/TimeBaseLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiRuntimeLib.h>
+
+#include "LsRealTimeClock.h"
+
+STATIC BOOLEAN    mInitialized = FALSE;
+STATIC EFI_EVENT  mRtcVirtualAddrChangeEvent;
+STATIC UINTN      mRtcBase;
+
+/*
+  Enable Real-time clock.
+
+  @param VOID
+
+  @retval  VOID
+ */
+VOID
+InitRtc (
+  VOID
+  )
+{
+  UINTN              Val;
+  EFI_HOB_GUID_TYPE  *GuidHob   = NULL;
+  VOID               *DataInHob = NULL;
+
+  if (!mInitialized) {
+    /* Enable rtc */
+    GuidHob = GetFirstGuidHob (&mRtcRegisterBaseAddressGuid);
+    if (GuidHob) {
+      DataInHob = GET_GUID_HOB_DATA (GuidHob);
+      mRtcBase  = (UINT64)(*(UINTN *)DataInHob);
+      Val       = MmioRead32 (mRtcBase + RTC_CTRL_REG);
+      Val      |= TOY_ENABLE_BIT | OSC_ENABLE_BIT;
+      MmioWrite32 (mRtcBase + RTC_CTRL_REG, Val);
+      mInitialized = TRUE;
+    } else {
+      DebugPrint (EFI_D_INFO, "RTC register address not found!\n");
+      ASSERT (FALSE);
+    }
+  }
+}
+
+/**
+  Returns the current time and date information, and the time-keeping capabilities
+  of the hardware platform.
+
+  @param  Time                   A pointer to storage to receive a snapshot of the current time.
+  @param  Capabilities           An optional pointer to a buffer to receive the real time clock
+                                 device's capabilities.
+
+  @retval EFI_SUCCESS            The operation completed successfully.
+  @retval EFI_INVALID_PARAMETER  Time is NULL.
+  @retval EFI_DEVICE_ERROR       The time could not be retrieved due to hardware error.
+  @retval EFI_SECURITY_VIOLATION The time could not be retrieved due to an authentication failure.
+**/
+EFI_STATUS
+EFIAPI
+LibGetTime (
+  OUT EFI_TIME               *Time,
+  OUT EFI_TIME_CAPABILITIES  *Capabilities
+  )
+{
+  UINT32  Val;
+
+  // Ensure Time is a valid pointer
+  if (Time == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  Val        = MmioRead32 (mRtcBase + TOY_READ1_REG);
+  Time->Year = Val + 1900;
+
+  Val              = MmioRead32 (mRtcBase + TOY_READ0_REG);
+  Time->Month      = (Val >> TOY_MON_SHIFT) & TOY_MON_MASK;
+  Time->Day        = (Val >> TOY_DAY_SHIFT) & TOY_DAY_MASK;
+  Time->Hour       = (Val >> TOY_HOUR_SHIFT) & TOY_HOUR_MASK;
+  Time->Minute     = (Val >> TOY_MIN_SHIFT) & TOY_MIN_MASK;
+  Time->Second     = (Val >> TOY_SEC_SHIFT) & TOY_SEC_MASK;
+  Time->Nanosecond = 0;
+  return EFI_SUCCESS;
+}
+
+/**
+  Sets the current local time and date information.
+
+  @param  Time                  A pointer to the current time.
+
+  @retval EFI_SUCCESS           The operation completed successfully.
+  @retval EFI_INVALID_PARAMETER A time field is out of range.
+  @retval EFI_DEVICE_ERROR      The time could not be set due due to hardware error.
+**/
+EFI_STATUS
+EFIAPI
+LibSetTime (
+  IN  EFI_TIME  *Time
+  )
+{
+  UINT32  Val;
+
+  // Initialize the hardware if not already done
+
+  Val  = 0;
+  Val |= (Time->Second << TOY_SEC_SHIFT);
+  Val |= (Time->Minute << TOY_MIN_SHIFT);
+  Val |= (Time->Hour   << TOY_HOUR_SHIFT);
+  Val |= (Time->Day    << TOY_DAY_SHIFT);
+  Val |= (Time->Month  << TOY_MON_SHIFT);
+  MmioWrite32 (mRtcBase + TOY_WRITE0_REG, Val);
+
+  Val = Time->Year - 1900;
+  MmioWrite32 (mRtcBase + TOY_WRITE1_REG, Val);
+  return EFI_SUCCESS;
+}
+
+/**
+  Returns the current wakeup alarm clock setting.
+
+  @param  Enabled               Indicates if the alarm is currently enabled or disabled.
+  @param  Pending               Indicates if the alarm signal is pending and requires acknowledgement.
+  @param  Time                  The current alarm setting.
+
+  @retval EFI_SUCCESS           The alarm settings were returned.
+  @retval EFI_INVALID_PARAMETER Any parameter is NULL.
+  @retval EFI_DEVICE_ERROR      The wakeup time could not be retrieved due to a hardware error.
+**/
+EFI_STATUS
+EFIAPI
+LibGetWakeupTime (
+  OUT BOOLEAN   *Enabled,
+  OUT BOOLEAN   *Pending,
+  OUT EFI_TIME  *Time
+  )
+{
+  // Not a required feature
+  return EFI_UNSUPPORTED;
+}
+
+/**
+  Sets the system wakeup alarm clock time.
+
+  @param  Enabled               Enable or disable the wakeup alarm.
+  @param  Time                  If Enable is TRUE, the time to set the wakeup alarm for.
+
+  @retval EFI_SUCCESS           If Enable is TRUE, then the wakeup alarm was enabled. If
+                                Enable is FALSE, then the wakeup alarm was disabled.
+  @retval EFI_INVALID_PARAMETER A time field is out of range.
+  @retval EFI_DEVICE_ERROR      The wakeup time could not be set due to a hardware error.
+  @retval EFI_UNSUPPORTED       A wakeup timer is not supported on this platform.
+**/
+EFI_STATUS
+EFIAPI
+LibSetWakeupTime (
+  IN BOOLEAN    Enabled,
+  OUT EFI_TIME  *Time
+  )
+{
+  // Not a required feature
+  return EFI_UNSUPPORTED;
+}
+
+/**
+  Fixup internal data so that EFI can be call in virtual mode.
+  Call the passed in Child Notify event and convert any pointers in
+  lib to virtual mode.
+
+  @param[in]    Event   The Event that is being processed
+  @param[in]    Context Event Context
+**/
+VOID
+EFIAPI
+VirtualNotifyEvent (
+  IN EFI_EVENT  Event,
+  IN VOID       *Context
+  )
+{
+  //
+  // Only needed if you are going to support the OS calling RTC functions in virtual mode.
+  // You will need to call EfiConvertPointer (). To convert any stored physical addresses
+  // to virtual address. After the OS transitions to calling in virtual mode, all future
+  // runtime calls will be made in virtual mode.
+  //
+  EfiConvertPointer (0x0, (VOID **)&mRtcBase);
+  return;
+}
+
+/** Add the RTC controller address range to the memory map.
+
+  @param [in]  ImageHandle  The handle to the image.
+  @param [in]  RtcPageBase  Base address of the RTC controller.
+
+  @retval EFI_SUCCESS             Success.
+  @retval EFI_INVALID_PARAMETER   A parameter is invalid.
+  @retval EFI_NOT_FOUND           Flash device not found.
+**/
+EFI_STATUS
+KvmtoolRtcMapMemory (
+  IN EFI_HANDLE            ImageHandle,
+  IN EFI_PHYSICAL_ADDRESS  RtcPageBase
+  )
+{
+  EFI_STATUS  Status;
+
+  Status = gDS->AddMemorySpace (
+                  EfiGcdMemoryTypeMemoryMappedIo,
+                  RtcPageBase,
+                  EFI_PAGE_SIZE,
+                  EFI_MEMORY_UC | EFI_MEMORY_RUNTIME
+                  );
+  if (EFI_ERROR (Status)) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "Failed to add memory space. Status = %r\n",
+      Status
+      ));
+    return Status;
+  }
+
+  Status = gDS->AllocateMemorySpace (
+                  EfiGcdAllocateAddress,
+                  EfiGcdMemoryTypeMemoryMappedIo,
+                  0,
+                  EFI_PAGE_SIZE,
+                  &RtcPageBase,
+                  ImageHandle,
+                  NULL
+                  );
+  if (EFI_ERROR (Status)) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "Failed to allocate memory space. Status = %r\n",
+      Status
+      ));
+    gDS->RemoveMemorySpace (
+           RtcPageBase,
+           EFI_PAGE_SIZE
+           );
+    return Status;
+  }
+
+  Status = gDS->SetMemorySpaceAttributes (
+                  RtcPageBase,
+                  EFI_PAGE_SIZE,
+                  EFI_MEMORY_UC | EFI_MEMORY_RUNTIME
+                  );
+  if (EFI_ERROR (Status)) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "Failed to set memory attributes. Status = %r\n",
+      Status
+      ));
+
+    gDS->FreeMemorySpace (
+           RtcPageBase,
+           EFI_PAGE_SIZE
+           );
+
+    gDS->RemoveMemorySpace (
+           RtcPageBase,
+           EFI_PAGE_SIZE
+           );
+  }
+
+  return Status;
+}
+
+/**
+  This is the declaration of an EFI image entry point. This can be the entry point to an application
+  written to this specification, an EFI boot service driver, or an EFI runtime driver.
+
+  @param  ImageHandle           Handle that identifies the loaded image.
+  @param  SystemTable           System Table for this image.
+
+  @retval EFI_SUCCESS           The operation completed successfully.
+**/
+EFI_STATUS
+EFIAPI
+LibRtcInitialize (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  )
+{
+  EFI_STATUS  Status;
+
+  InitRtc ();
+  Status = KvmtoolRtcMapMemory (ImageHandle, (mRtcBase & ~EFI_PAGE_MASK));
+  if (EFI_ERROR (Status)) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "Failed to map memory for loongson 7A RTC. Status = %r\n",
+      Status
+      ));
+    return Status;
+  }
+
+  //
+  // Register for the virtual address change event
+  //
+  Status = gBS->CreateEventEx (
+                  EVT_NOTIFY_SIGNAL,
+                  TPL_NOTIFY,
+                  VirtualNotifyEvent,
+                  NULL,
+                  &gEfiEventVirtualAddressChangeGuid,
+                  &mRtcVirtualAddrChangeEvent
+                  );
+  ASSERT_EFI_ERROR (Status);
+  return Status;
+}
diff --git a/OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/DxeLsRealTimeClockLib.inf b/OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/DxeLsRealTimeClockLib.inf
new file mode 100644
index 0000000000..3b8a21b25c
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/DxeLsRealTimeClockLib.inf
@@ -0,0 +1,42 @@
+## @file
+#  LoongArch64 CPU Real Time Clock DXE Phase Library.
+#
+# Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = LsRealTimeClockLib
+  FILE_GUID                      = 9793a3da-1869-4fdf-88b1-c6484341f50b
+  MODULE_TYPE                    = DXE_DRIVER
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = RealTimeClockLib
+
+#
+#  VALID_ARCHITECTURES           = LOONGARCH64
+#
+
+[Sources.common]
+  DxeLsRealTimeClockLib.c
+
+[Packages]
+  MdePkg/MdePkg.dec
+  EmbeddedPkg/EmbeddedPkg.dec
+
+[LibraryClasses]
+  IoLib
+  UefiLib
+  DebugLib
+  PcdLib
+  HobLib
+  DxeServicesTableLib
+  UefiRuntimeLib
+
+[Guids]
+  gEfiEventVirtualAddressChangeGuid
+
+[Depex]
+  TRUE
diff --git a/OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/LsRealTimeClock.h b/OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/LsRealTimeClock.h
new file mode 100644
index 0000000000..fc8663da56
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/LsRealTimeClock.h
@@ -0,0 +1,47 @@
+/** @file
+  Implement EFI RealTimeClock runtime services via RTC Lib.
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef LS_REAL_TIME_CLOCK_H_
+#define LS_REAL_TIME_CLOCK_H_
+
+#define TOY_WRITE0_REG  0x24
+#define TOY_WRITE1_REG  0x28
+#define TOY_READ0_REG   0x2c
+#define TOY_READ1_REG   0x30
+#define RTC_CTRL_REG    0x40
+
+/* TOY Enable bits */
+#define RTC_ENABLE_BIT  (1UL << 13)
+#define TOY_ENABLE_BIT  (1UL << 11)
+#define OSC_ENABLE_BIT  (1UL << 8)
+
+/*
+ * shift bits and filed mask
+ */
+#define TOY_MON_MASK   0x3f
+#define TOY_DAY_MASK   0x1f
+#define TOY_HOUR_MASK  0x1f
+#define TOY_MIN_MASK   0x3f
+#define TOY_SEC_MASK   0x3f
+#define TOY_MSEC_MASK  0xf
+
+#define TOY_MON_SHIFT   26
+#define TOY_DAY_SHIFT   21
+#define TOY_HOUR_SHIFT  16
+#define TOY_MIN_SHIFT   10
+#define TOY_SEC_SHIFT   4
+
+#define RTC_REGISTER_ADDRESS_HOB_GUID \
+  { \
+    0x0d7c012b, 0x79c1, 0xfa58, { 0x6f, 0x91, 0xbe, 0x3e, 0xee, 0x46, 0x5f, 0x71 } \
+  }
+
+EFI_GUID  mRtcRegisterBaseAddressGuid = RTC_REGISTER_ADDRESS_HOB_GUID;
+
+#endif // LS_REAL_TIME_CLOCK_H_
diff --git a/OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/PeiLsRealTimeClockLib.c b/OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/PeiLsRealTimeClockLib.c
new file mode 100644
index 0000000000..d6f71f66ad
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/PeiLsRealTimeClockLib.c
@@ -0,0 +1,31 @@
+/** @file
+  Implement EFI RealTimeClock PEI phase RTC Lib.
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Library/HobLib.h>
+
+#include "LsRealTimeClock.h"
+
+VOID
+SaveRtcRegisterAddressHob (
+  UINT64  RtcRegisterBase
+  )
+{
+  UINT64  Data64;
+
+  //
+  // Build location of RTC register base address buffer in HOB
+  //
+  Data64 = (UINT64)(UINTN)RtcRegisterBase;
+
+  BuildGuidDataHob (
+    &mRtcRegisterBaseAddressGuid,
+    (VOID *)&Data64,
+    sizeof (UINT64)
+    );
+}
diff --git a/OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/PeiLsRealTimeClockLib.inf b/OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/PeiLsRealTimeClockLib.inf
new file mode 100644
index 0000000000..8b78040331
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/LsRealTimeClockLib/PeiLsRealTimeClockLib.inf
@@ -0,0 +1,29 @@
+## @file
+#  LoongArch64 CPU Real Time Clock PEI Phase Library.
+#
+# Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = PeiLsRealTimeClockLib
+  FILE_GUID                      = d4358430-15ec-9358-1b12-26dab955e9c6
+  MODULE_TYPE                    = PEIM
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = RealTimeClockLib|PEIM
+
+#
+#  VALID_ARCHITECTURES           = LOONGARCH64
+#
+
+[Sources.common]
+  PeiLsRealTimeClockLib.c
+
+[Packages]
+  MdePkg/MdePkg.dec
+
+[LibraryClasses]
+  HobLib
-- 
2.27.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#110532): https://edk2.groups.io/g/devel/message/110532
Mute This Topic: https://groups.io/mt/102342178/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* [edk2-devel] [PATCH v1 23/29] OvmfPkg/LoongArchVirt: Add PeiServiceTablePointerLib
       [not found] <20231102134249.3983594-1-lichao@loongson.cn>
                   ` (12 preceding siblings ...)
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 21/29] OvmfPkg/LoongArchVirt: Add real time clock library Chao Li
@ 2023-11-02 13:42 ` Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 24/29] OvmfPkg/LoongArchVirt: Add platform boot manager library Chao Li
                   ` (3 subsequent siblings)
  17 siblings, 0 replies; 18+ messages in thread
From: Chao Li @ 2023-11-02 13:42 UTC (permalink / raw)
  To: devel
  Cc: Ard Biesheuvel, Jiewen Yao, Jordan Justen, Gerd Hoffmann,
	Xianglai Li, Bibo Mao

Use a register to save PeiServiceTable pointer. This Library provides
PeiServiceTable pointer saveing and retrieval serivces.

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

Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Chao Li <lichao@loongson.cn>
Co-authored-by: Xianglai Li <lixianglai@loongson.cn>
Co-authored-by: Bibo Mao <maobibo@loongson.cn>
---
 .../PeiServicesTablePointer.c                 | 75 +++++++++++++++++++
 .../PeiServicesTablePointerLib.inf            | 31 ++++++++
 2 files changed, 106 insertions(+)
 create mode 100644 OvmfPkg/LoongArchVirt/Library/PeiServicesTablePointerLib/PeiServicesTablePointer.c
 create mode 100644 OvmfPkg/LoongArchVirt/Library/PeiServicesTablePointerLib/PeiServicesTablePointerLib.inf

diff --git a/OvmfPkg/LoongArchVirt/Library/PeiServicesTablePointerLib/PeiServicesTablePointer.c b/OvmfPkg/LoongArchVirt/Library/PeiServicesTablePointerLib/PeiServicesTablePointer.c
new file mode 100644
index 0000000000..dcbcb50131
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/PeiServicesTablePointerLib/PeiServicesTablePointer.c
@@ -0,0 +1,75 @@
+/** @file
+  PEI Services Table Pointer Library.
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <PiPei.h>
+#include <Library/PeiServicesTablePointerLib.h>
+#include <Library/DebugLib.h>
+#include <Library/BaseLib.h>
+#include <Register/LoongArch64/Csr.h>
+
+/**
+  Caches a pointer PEI Services Table.
+
+  Caches the pointer to the PEI Services Table specified by PeiServicesTablePointer
+  in a platform specific manner.
+
+  If PeiServicesTablePointer is NULL, then ASSERT ().
+
+  @param    PeiServicesTablePointer   The address of PeiServices pointer.
+**/
+VOID
+EFIAPI
+SetPeiServicesTablePointer (
+  IN CONST EFI_PEI_SERVICES  **PeiServicesTablePointer
+  )
+{
+  CsrWrite (LOONGARCH_CSR_KS0, (UINTN)PeiServicesTablePointer);
+}
+
+/**
+  Retrieves the cached value of the PEI Services Table pointer.
+
+  Returns the cached value of the PEI Services Table pointer in a CPU specific manner
+  as specified in the CPU binding section of the Platform Initialization Pre-EFI
+  Initialization Core Interface Specification.
+
+  If the cached PEI Services Table pointer is NULL, then ASSERT ().
+
+  @return  The pointer to PeiServices.
+**/
+CONST EFI_PEI_SERVICES **
+EFIAPI
+GetPeiServicesTablePointer (
+  VOID
+  )
+{
+  return (CONST EFI_PEI_SERVICES **)(CsrRead (LOONGARCH_CSR_KS0));
+}
+
+/**
+Perform CPU specific actions required to migrate the PEI Services Table
+pointer from temporary RAM to permanent RAM.
+
+For IA32 CPUs, the PEI Services Table pointer is stored in the 4 bytes
+immediately preceding the Interrupt Descriptor Table (IDT) in memory.
+For X64 CPUs, the PEI Services Table pointer is stored in the 8 bytes
+immediately preceding the Interrupt Descriptor Table (IDT) in memory.
+For Itanium and ARM CPUs, a the PEI Services Table Pointer is stored in
+a dedicated CPU register.  This means that there is no memory storage
+associated with storing the PEI Services Table pointer, so no additional
+migration actions are required for Itanium or ARM CPUs.
+**/
+VOID
+EFIAPI
+MigratePeiServicesTablePointer (
+  VOID
+  )
+{
+  return;
+}
diff --git a/OvmfPkg/LoongArchVirt/Library/PeiServicesTablePointerLib/PeiServicesTablePointerLib.inf b/OvmfPkg/LoongArchVirt/Library/PeiServicesTablePointerLib/PeiServicesTablePointerLib.inf
new file mode 100644
index 0000000000..274cb2f781
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/PeiServicesTablePointerLib/PeiServicesTablePointerLib.inf
@@ -0,0 +1,31 @@
+## @file
+#  PEI Services Table Pointer Library.
+#
+#  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = PeiServicesTablePointerLib
+  FILE_GUID                      = 098B0DB0-AD01-8886-D409-90CBC7E89154
+  MODULE_TYPE                    = PEIM
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = PeiServicesTablePointerLib|PEIM PEI_CORE SEC
+
+#
+#  VALID_ARCHITECTURES           = LOONGARCH64
+#
+
+[Sources]
+  PeiServicesTablePointer.c
+
+[Packages]
+  MdePkg/MdePkg.dec
+
+[LibraryClasses]
+  BaseLib
+  DebugLib
+
+[Pcd]
-- 
2.27.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#110541): https://edk2.groups.io/g/devel/message/110541
Mute This Topic: https://groups.io/mt/102342297/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* [edk2-devel] [PATCH v1 24/29] OvmfPkg/LoongArchVirt: Add platform boot manager library
       [not found] <20231102134249.3983594-1-lichao@loongson.cn>
                   ` (13 preceding siblings ...)
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 23/29] OvmfPkg/LoongArchVirt: Add PeiServiceTablePointerLib Chao Li
@ 2023-11-02 13:42 ` Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 25/29] OvmfPkg/LoongArchVirt: Add FdtQemuFwCfgLib Chao Li
                   ` (2 subsequent siblings)
  17 siblings, 0 replies; 18+ messages in thread
From: Chao Li @ 2023-11-02 13:42 UTC (permalink / raw)
  To: devel
  Cc: Ard Biesheuvel, Jiewen Yao, Jordan Justen, Gerd Hoffmann,
	Xianglai Li, Bibo Mao

This library is provides boot mananger interfaces, and it is referenced
from ArmVirtPkg.

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

Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Chao Li <lichao@loongson.cn>
Co-authored-by: Xianglai Li <lixianglai@loongson.cn>
Co-authored-by: Bibo Mao <maobibo@loongson.cn>
---
 .../PlatformBootManagerLib/PlatformBm.c       | 829 ++++++++++++++++++
 .../PlatformBootManagerLib/PlatformBm.h       | 112 +++
 .../PlatformBootManagerLib.inf                |  73 ++
 .../PlatformBootManagerLib/QemuKernel.c       |  81 ++
 4 files changed, 1095 insertions(+)
 create mode 100644 OvmfPkg/LoongArchVirt/Library/PlatformBootManagerLib/PlatformBm.c
 create mode 100644 OvmfPkg/LoongArchVirt/Library/PlatformBootManagerLib/PlatformBm.h
 create mode 100644 OvmfPkg/LoongArchVirt/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf
 create mode 100644 OvmfPkg/LoongArchVirt/Library/PlatformBootManagerLib/QemuKernel.c

diff --git a/OvmfPkg/LoongArchVirt/Library/PlatformBootManagerLib/PlatformBm.c b/OvmfPkg/LoongArchVirt/Library/PlatformBootManagerLib/PlatformBm.c
new file mode 100644
index 0000000000..bc12eaa108
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/PlatformBootManagerLib/PlatformBm.c
@@ -0,0 +1,829 @@
+/** @file
+  Implementation for PlatformBootManagerLib library class interfaces.
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <IndustryStandard/Pci22.h>
+#include <Library/BootLogoLib.h>
+#include <Library/PcdLib.h>
+#include <Library/QemuBootOrderLib.h>
+#include <Library/UefiBootManagerLib.h>
+#include <Protocol/FirmwareVolume2.h>
+#include <Protocol/LoadedImage.h>
+#include <Protocol/PciIo.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/DebugLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/UefiLib.h>
+#include <Library/BaseMemoryLib.h>
+#include "PlatformBm.h"
+
+STATIC PLATFORM_SERIAL_CONSOLE  mSerialConsole = {
+  //
+  // VENDOR_DEVICE_PATH SerialDxe
+  //
+  {
+    { HARDWARE_DEVICE_PATH,  HW_VENDOR_DP, DP_NODE_LEN (VENDOR_DEVICE_PATH) },
+    SERIAL_DXE_FILE_GUID
+  },
+
+  //
+  // UART_DEVICE_PATH Uart
+  //
+  {
+    { MESSAGING_DEVICE_PATH, MSG_UART_DP,  DP_NODE_LEN (UART_DEVICE_PATH)   },
+    0,                                      // Reserved
+    FixedPcdGet64 (PcdUartDefaultBaudRate), // BaudRate
+    FixedPcdGet8 (PcdUartDefaultDataBits),  // DataBits
+    FixedPcdGet8 (PcdUartDefaultParity),    // Parity
+    FixedPcdGet8 (PcdUartDefaultStopBits)   // StopBits
+  },
+
+  //
+  // VENDOR_DEFINED_DEVICE_PATH TermType
+  //
+  {
+    {
+      MESSAGING_DEVICE_PATH, MSG_VENDOR_DP,
+      DP_NODE_LEN (VENDOR_DEFINED_DEVICE_PATH)
+    }
+    //
+    // Guid to be filled in dynamically
+    //
+  },
+
+  //
+  // EFI_DEVICE_PATH_PROTOCOL End
+  //
+  {
+    END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE,
+    DP_NODE_LEN (EFI_DEVICE_PATH_PROTOCOL)
+  }
+};
+
+STATIC PLATFORM_USB_KEYBOARD  mUsbKeyboard = {
+  //
+  // USB_CLASS_DEVICE_PATH Keyboard
+  //
+  {
+    {
+      MESSAGING_DEVICE_PATH, MSG_USB_CLASS_DP,
+      DP_NODE_LEN (USB_CLASS_DEVICE_PATH)
+    },
+    0xFFFF, // VendorId: any
+    0xFFFF, // ProductId: any
+    3,      // DeviceClass: HID
+    1,      // DeviceSubClass: boot
+    1       // DeviceProtocol: keyboard
+  },
+
+  //
+  // EFI_DEVICE_PATH_PROTOCOL End
+  //
+  {
+    END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE,
+    DP_NODE_LEN (EFI_DEVICE_PATH_PROTOCOL)
+  }
+};
+
+/**
+  Locate all handles that carry the specified protocol, filter them with a
+  callback function, and pass each handle that passes the filter to another
+  callback.
+
+  @param[in] ProtocolGuid  The protocol to look for.
+
+  @param[in] Filter        The filter function to pass each handle to. If this
+                           parameter is NULL, then all handles are processed.
+
+  @param[in] Process       The callback function to pass each handle to that
+                           clears the filter.
+**/
+VOID
+FilterAndProcess (
+  IN EFI_GUID           *ProtocolGuid,
+  IN FILTER_FUNCTION    Filter         OPTIONAL,
+  IN CALLBACK_FUNCTION  Process
+  )
+{
+  EFI_STATUS  Status;
+  EFI_HANDLE  *Handles;
+  UINTN       NoHandles;
+  UINTN       Idx;
+
+  Status = gBS->LocateHandleBuffer (
+                  ByProtocol,
+                  ProtocolGuid,
+                  NULL /* SearchKey */,
+                  &NoHandles,
+                  &Handles
+                  );
+  if (EFI_ERROR (Status)) {
+    //
+    // This is not an error, just an informative condition.
+    //
+    DEBUG ((
+      DEBUG_VERBOSE,
+      "%a: %g: %r\n",
+      __FUNCTION__,
+      ProtocolGuid,
+      Status
+      ));
+    return;
+  }
+
+  ASSERT (NoHandles > 0);
+  for (Idx = 0; Idx < NoHandles; ++Idx) {
+    CHAR16         *DevicePathText;
+    STATIC CHAR16  Fallback[] = L"<device path unavailable>";
+
+    //
+    // The ConvertDevicePathToText () function handles NULL input transparently.
+    //
+    DevicePathText = ConvertDevicePathToText (
+                       DevicePathFromHandle (Handles[Idx]),
+                       FALSE, // DisplayOnly
+                       FALSE  // AllowShortcuts
+                       );
+    if (DevicePathText == NULL) {
+      DevicePathText = Fallback;
+    }
+
+    if ((Filter == NULL) || (Filter (Handles[Idx], DevicePathText))) {
+      Process (Handles[Idx], DevicePathText);
+    }
+
+    if (DevicePathText != Fallback) {
+      FreePool (DevicePathText);
+    }
+  }
+
+  gBS->FreePool (Handles);
+}
+
+/**
+  This FILTER_FUNCTION checks if a handle corresponds to a PCI display device.
+
+  @param  Handle   The handle to check
+  @param  ReportText   A pointer to a string at the time of the error.
+
+  @retval    TURE     THe  handle corresponds to a PCI display device.
+  @retval    FALSE    THe  handle does not corresponds to a PCI display device.
+**/
+BOOLEAN
+EFIAPI
+IsPciDisplay (
+  IN EFI_HANDLE    Handle,
+  IN CONST CHAR16  *ReportText
+  )
+{
+  EFI_STATUS           Status;
+  EFI_PCI_IO_PROTOCOL  *PciIo;
+  PCI_TYPE00           Pci;
+
+  Status = gBS->HandleProtocol (
+                  Handle,
+                  &gEfiPciIoProtocolGuid,
+                  (VOID **)&PciIo
+                  );
+  if (EFI_ERROR (Status)) {
+    //
+    // This is not an error worth reporting.
+    //
+    return FALSE;
+  }
+
+  Status = PciIo->Pci.Read (
+                        PciIo,
+                        EfiPciIoWidthUint32,
+                        0 /* Offset */,
+                        sizeof Pci / sizeof (UINT32),
+                        &Pci
+                        );
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_ERROR, "%a: %s: %r\n", __FUNCTION__, ReportText, Status));
+    return FALSE;
+  }
+
+  return IS_PCI_DISPLAY (&Pci);
+}
+
+/**
+  This CALLBACK_FUNCTION attempts to connect a handle non-recursively, asking
+  the matching driver to produce all first-level child handles.
+
+  @param  Handle   The handle to connect.
+  @param  ReportText   A pointer to a string at the time of the error.
+
+  @retval  VOID
+**/
+VOID
+EFIAPI
+Connect (
+  IN EFI_HANDLE    Handle,
+  IN CONST CHAR16  *ReportText
+  )
+{
+  EFI_STATUS  Status;
+
+  Status = gBS->ConnectController (
+                  Handle, // ControllerHandle
+                  NULL,   // DriverImageHandle
+                  NULL,   // RemainingDevicePath -- produce all children
+                  FALSE   // Recursive
+                  );
+  DEBUG ((
+    EFI_ERROR (Status) ? DEBUG_ERROR : DEBUG_VERBOSE,
+    "%a: %s: %r\n",
+    __FUNCTION__,
+    ReportText,
+    Status
+    ));
+}
+
+/**
+  This CALLBACK_FUNCTION retrieves the EFI_DEVICE_PATH_PROTOCOL from the
+  handle, and adds it to ConOut and ErrOut.
+
+  @param  Handle   The handle to retrieves.
+  @param  ReportText   A pointer to a string at the time of the error.
+
+  @retval  VOID
+**/
+VOID
+EFIAPI
+AddOutput (
+  IN EFI_HANDLE    Handle,
+  IN CONST CHAR16  *ReportText
+  )
+{
+  EFI_STATUS                Status;
+  EFI_DEVICE_PATH_PROTOCOL  *DevicePath;
+
+  DevicePath = DevicePathFromHandle (Handle);
+  if (DevicePath == NULL) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "%a: %s: handle %p: device path not found\n",
+      __FUNCTION__,
+      ReportText,
+      Handle
+      ));
+    return;
+  }
+
+  Status = EfiBootManagerUpdateConsoleVariable (ConOut, DevicePath, NULL);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "%a: %s: adding to ConOut: %r\n",
+      __FUNCTION__,
+      ReportText,
+      Status
+      ));
+    return;
+  }
+
+  Status = EfiBootManagerUpdateConsoleVariable (ErrOut, DevicePath, NULL);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "%a: %s: adding to ErrOut: %r\n",
+      __FUNCTION__,
+      ReportText,
+      Status
+      ));
+    return;
+  }
+
+  DEBUG ((
+    DEBUG_VERBOSE,
+    "%a: %s: added to ConOut and ErrOut\n",
+    __FUNCTION__,
+    ReportText
+    ));
+}
+
+/**
+  Register the boot option.
+
+  @param  FileGuid      File Guid.
+  @param  Description   Option descriptor.
+  @param  Attributes    Option  Attributes.
+
+  @retval  VOID
+**/
+VOID
+PlatformRegisterFvBootOption (
+  IN EFI_GUID  *FileGuid,
+  IN CHAR16    *Description,
+  IN UINT32    Attributes
+  )
+{
+  EFI_STATUS                         Status;
+  INTN                               OptionIndex;
+  EFI_BOOT_MANAGER_LOAD_OPTION       NewOption;
+  EFI_BOOT_MANAGER_LOAD_OPTION       *BootOptions;
+  UINTN                              BootOptionCount;
+  MEDIA_FW_VOL_FILEPATH_DEVICE_PATH  FileNode;
+  EFI_LOADED_IMAGE_PROTOCOL          *LoadedImage;
+  EFI_DEVICE_PATH_PROTOCOL           *DevicePath;
+
+  Status = gBS->HandleProtocol (
+                  gImageHandle,
+                  &gEfiLoadedImageProtocolGuid,
+                  (VOID **)&LoadedImage
+                  );
+  ASSERT_EFI_ERROR (Status);
+
+  EfiInitializeFwVolDevicepathNode (&FileNode, FileGuid);
+  DevicePath = DevicePathFromHandle (LoadedImage->DeviceHandle);
+  ASSERT (DevicePath != NULL);
+  DevicePath = AppendDevicePathNode (
+                 DevicePath,
+                 (EFI_DEVICE_PATH_PROTOCOL *)&FileNode
+                 );
+  ASSERT (DevicePath != NULL);
+
+  Status = EfiBootManagerInitializeLoadOption (
+             &NewOption,
+             LoadOptionNumberUnassigned,
+             LoadOptionTypeBoot,
+             Attributes,
+             Description,
+             DevicePath,
+             NULL,
+             0
+             );
+  ASSERT_EFI_ERROR (Status);
+  FreePool (DevicePath);
+
+  BootOptions = EfiBootManagerGetLoadOptions (
+                  &BootOptionCount,
+                  LoadOptionTypeBoot
+                  );
+
+  OptionIndex = EfiBootManagerFindLoadOption (
+                  &NewOption,
+                  BootOptions,
+                  BootOptionCount
+                  );
+
+  if (OptionIndex == -1) {
+    Status = EfiBootManagerAddLoadOptionVariable (&NewOption, MAX_UINTN);
+    ASSERT_EFI_ERROR (Status);
+  }
+
+  EfiBootManagerFreeLoadOption (&NewOption);
+  EfiBootManagerFreeLoadOptions (BootOptions, BootOptionCount);
+}
+
+/**
+  Remove all MemoryMapped (...)/FvFile (...) and Fv (...)/FvFile (...) boot options
+  whose device paths do not resolve exactly to an FvFile in the system.
+
+  This removes any boot options that point to binaries built into the firmware
+  and have become stale due to any of the following:
+  - FvMain's base address or size changed (historical),
+  - FvMain's FvNameGuid changed,
+  - the FILE_GUID of the pointed-to binary changed,
+  - the referenced binary is no longer built into the firmware.
+
+  EfiBootManagerFindLoadOption () used in PlatformRegisterFvBootOption () only
+  avoids exact duplicates.
+**/
+VOID
+RemoveStaleFvFileOptions (
+  VOID
+  )
+{
+  EFI_BOOT_MANAGER_LOAD_OPTION  *BootOptions;
+  UINTN                         BootOptionCount;
+  UINTN                         Index;
+
+  BootOptions = EfiBootManagerGetLoadOptions (
+                  &BootOptionCount,
+                  LoadOptionTypeBoot
+                  );
+
+  for (Index = 0; Index < BootOptionCount; ++Index) {
+    EFI_DEVICE_PATH_PROTOCOL  *Node1, *Node2, *SearchNode;
+    EFI_STATUS                Status;
+    EFI_HANDLE                FvHandle;
+
+    //
+    // If the device path starts with neither MemoryMapped (...) nor Fv (...),
+    // then keep the boot option.
+    //
+    Node1 = BootOptions[Index].FilePath;
+    if (!((DevicePathType (Node1) == HARDWARE_DEVICE_PATH) &&
+          (DevicePathSubType (Node1) == HW_MEMMAP_DP)) &&
+        !((DevicePathType (Node1) == MEDIA_DEVICE_PATH) &&
+          (DevicePathSubType (Node1) == MEDIA_PIWG_FW_VOL_DP)))
+    {
+      continue;
+    }
+
+    //
+    // If the second device path node is not FvFile (...), then keep the boot
+    // option.
+    //
+    Node2 = NextDevicePathNode (Node1);
+    if ((DevicePathType (Node2) != MEDIA_DEVICE_PATH) ||
+        (DevicePathSubType (Node2) != MEDIA_PIWG_FW_FILE_DP))
+    {
+      continue;
+    }
+
+    //
+    // Locate the Firmware Volume2 protocol instance that is denoted by the
+    // boot option. If this lookup fails (i.e., the boot option references a
+    // firmware volume that doesn't exist), then we'll proceed to delete the
+    // boot option.
+    //
+    SearchNode = Node1;
+    Status     = gBS->LocateDevicePath (
+                        &gEfiFirmwareVolume2ProtocolGuid,
+                        &SearchNode,
+                        &FvHandle
+                        );
+
+    if (!EFI_ERROR (Status)) {
+      //
+      // The firmware volume was found; now let's see if it contains the FvFile
+      // identified by GUID.
+      //
+      EFI_FIRMWARE_VOLUME2_PROTOCOL      *FvProtocol;
+      MEDIA_FW_VOL_FILEPATH_DEVICE_PATH  *FvFileNode;
+      UINTN                              BufferSize;
+      EFI_FV_FILETYPE                    FoundType;
+      EFI_FV_FILE_ATTRIBUTES             FileAttributes;
+      UINT32                             AuthenticationStatus;
+
+      Status = gBS->HandleProtocol (
+                      FvHandle,
+                      &gEfiFirmwareVolume2ProtocolGuid,
+                      (VOID **)&FvProtocol
+                      );
+      ASSERT_EFI_ERROR (Status);
+
+      FvFileNode = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)Node2;
+      //
+      // Buffer==NULL means we request metadata only: BufferSize, FoundType,
+      // FileAttributes.
+      //
+      Status = FvProtocol->ReadFile (
+                             FvProtocol,
+                             &FvFileNode->FvFileName, // NameGuid
+                             NULL,                    // Buffer
+                             &BufferSize,
+                             &FoundType,
+                             &FileAttributes,
+                             &AuthenticationStatus
+                             );
+      if (!EFI_ERROR (Status)) {
+        //
+        // The FvFile was found. Keep the boot option.
+        //
+        continue;
+      }
+    }
+
+    //
+    // Delete the boot option.
+    //
+    Status = EfiBootManagerDeleteLoadOptionVariable (
+               BootOptions[Index].OptionNumber,
+               LoadOptionTypeBoot
+               );
+    DEBUG_CODE_BEGIN ();
+    CHAR16  *DevicePathString;
+
+    DevicePathString = ConvertDevicePathToText (
+                         BootOptions[Index].FilePath,
+                         FALSE,
+                         FALSE
+                         );
+    DEBUG ((
+      EFI_ERROR (Status) ? EFI_D_WARN : DEBUG_VERBOSE,
+      "%a: removing stale Boot#%04x %s: %r\n",
+      __FUNCTION__,
+      (UINT32)BootOptions[Index].OptionNumber,
+      DevicePathString == NULL ? L"<unavailable>" : DevicePathString,
+      Status
+      ));
+    if (DevicePathString != NULL) {
+      FreePool (DevicePathString);
+    }
+
+    DEBUG_CODE_END ();
+  }
+
+  EfiBootManagerFreeLoadOptions (BootOptions, BootOptionCount);
+}
+
+/**
+  Register the boot option And Keys.
+
+  @param  VOID
+
+  @retval  VOID
+**/
+VOID
+PlatformRegisterOptionsAndKeys (
+  VOID
+  )
+{
+  EFI_STATUS                    Status;
+  EFI_INPUT_KEY                 Enter;
+  EFI_INPUT_KEY                 F2;
+  EFI_INPUT_KEY                 Esc;
+  EFI_BOOT_MANAGER_LOAD_OPTION  BootOption;
+
+  //
+  // Register ENTER as CONTINUE key
+  //
+  Enter.ScanCode    = SCAN_NULL;
+  Enter.UnicodeChar = CHAR_CARRIAGE_RETURN;
+
+  Status = EfiBootManagerRegisterContinueKeyOption (0, &Enter, NULL);
+  ASSERT_EFI_ERROR (Status);
+
+  //
+  // Map F2 and ESC to Boot Manager Menu
+  //
+  F2.ScanCode     = SCAN_F2;
+  F2.UnicodeChar  = CHAR_NULL;
+  Esc.ScanCode    = SCAN_ESC;
+  Esc.UnicodeChar = CHAR_NULL;
+  Status          = EfiBootManagerGetBootManagerMenu (&BootOption);
+  ASSERT_EFI_ERROR (Status);
+  Status = EfiBootManagerAddKeyOptionVariable (
+             NULL,
+             (UINT16)BootOption.OptionNumber,
+             0,
+             &F2,
+             NULL
+             );
+  ASSERT (Status == EFI_SUCCESS || Status == EFI_ALREADY_STARTED);
+  Status = EfiBootManagerAddKeyOptionVariable (
+             NULL,
+             (UINT16)BootOption.OptionNumber,
+             0,
+             &Esc,
+             NULL
+             );
+  ASSERT (Status == EFI_SUCCESS || Status == EFI_ALREADY_STARTED);
+}
+
+//
+// BDS Platform Functions
+//
+
+/**
+  Do the platform init, can be customized by OEM/IBV
+  Possible things that can be done in PlatformBootManagerBeforeConsole:
+  > Update console variable: 1. include hot-plug devices;
+  >                          2. Clear ConIn and add SOL for AMT
+  > Register new Driver#### or Boot####
+  > Register new Key####: e.g.: F12
+  > Signal ReadyToLock event
+  > Authentication action: 1. connect Auth devices;
+  >                        2. Identify auto logon user.
+**/
+VOID
+EFIAPI
+PlatformBootManagerBeforeConsole (
+  VOID
+  )
+{
+  RETURN_STATUS  PcdStatus;
+
+  //
+  // Signal EndOfDxe PI Event
+  //
+  EfiEventGroupSignal (&gEfiEndOfDxeEventGroupGuid);
+
+  //
+  // Dispatch deferred images after EndOfDxe event.
+  //
+  EfiBootManagerDispatchDeferredImages ();
+
+  //
+  // Locate the PCI root bridges and make the PCI bus driver connect each,
+  // non-recursively. This will produce a number of child handles with PciIo on
+  // them.
+  //
+  FilterAndProcess (&gEfiPciRootBridgeIoProtocolGuid, NULL, Connect);
+
+  //
+  // Signal the ACPI platform driver that it can download QEMU ACPI tables.
+  //
+  EfiEventGroupSignal (&gRootBridgesConnectedEventGroupGuid);
+
+  //
+  // Find all display class PCI devices (using the handles from the previous
+  // step), and connect them non-recursively. This should produce a number of
+  // child handles with GOPs on them.
+  //
+  FilterAndProcess (&gEfiPciIoProtocolGuid, IsPciDisplay, Connect);
+
+  //
+  // Now add the device path of all handles with GOP on them to ConOut and
+  // ErrOut.
+  //
+  FilterAndProcess (&gEfiGraphicsOutputProtocolGuid, NULL, AddOutput);
+
+  //
+  // Add the hardcoded short-form USB keyboard device path to ConIn.
+  //
+  EfiBootManagerUpdateConsoleVariable (
+    ConIn,
+    (EFI_DEVICE_PATH_PROTOCOL *)&mUsbKeyboard,
+    NULL
+    );
+
+  //
+  // Add the hardcoded serial console device path to ConIn, ConOut, ErrOut.
+  //
+  CopyGuid (&mSerialConsole.TermType.Guid, &gEfiTtyTermGuid);
+  EfiBootManagerUpdateConsoleVariable (
+    ConIn,
+    (EFI_DEVICE_PATH_PROTOCOL *)&mSerialConsole,
+    NULL
+    );
+  EfiBootManagerUpdateConsoleVariable (
+    ConOut,
+    (EFI_DEVICE_PATH_PROTOCOL *)&mSerialConsole,
+    NULL
+    );
+  EfiBootManagerUpdateConsoleVariable (
+    ErrOut,
+    (EFI_DEVICE_PATH_PROTOCOL *)&mSerialConsole,
+    NULL
+    );
+
+  //
+  // Set the front page timeout from the QEMU configuration.
+  //
+  PcdStatus = PcdSet16S (
+                PcdPlatformBootTimeOut,
+                GetFrontPageTimeoutFromQemu ()
+                );
+  ASSERT_RETURN_ERROR (PcdStatus);
+
+  //
+  // Register platform-specific boot options and keyboard shortcuts.
+  //
+  PlatformRegisterOptionsAndKeys ();
+}
+
+/**
+  Do the platform specific action after the console is ready
+  Possible things that can be done in PlatformBootManagerAfterConsole:
+  > Console post action:
+    > Dynamically switch output mode from 100x31 to 80x25 for certain senarino
+    > Signal console ready platform customized event
+  > Run diagnostics like memory testing
+  > Connect certain devices
+  > Dispatch aditional option roms
+  > Special boot: e.g.: USB boot, enter UI
+**/
+VOID
+EFIAPI
+PlatformBootManagerAfterConsole (
+  VOID
+  )
+{
+  //
+  // Show the splash screen.
+  //
+  BootLogoEnableLogo ();
+
+  //
+  // Connect the rest of the devices.
+  //
+  EfiBootManagerConnectAll ();
+
+  //
+  // Process QEMU's -kernel command line option. Note that the kernel booted
+  // this way should receive ACPI tables, which is why we connect all devices
+  // first (see above) -- PCI enumeration blocks ACPI table installation, if
+  // there is a PCI host.
+  //
+  TryRunningQemuKernel ();
+
+  //
+  // Enumerate all possible boot options, then filter and reorder them based on
+  // the QEMU configuration.
+  //
+  EfiBootManagerRefreshAllBootOption ();
+
+  //
+  // Register UEFI Shell
+  //
+  PlatformRegisterFvBootOption (
+    &gUefiShellFileGuid,
+    L"EFI Internal Shell",
+    LOAD_OPTION_ACTIVE
+    );
+
+  RemoveStaleFvFileOptions ();
+  SetBootOrderFromQemu ();
+}
+
+/**
+  This function is called each second during the boot manager waits the
+  timeout.
+
+  @param TimeoutRemain  The remaining timeout.
+**/
+VOID
+EFIAPI
+PlatformBootManagerWaitCallback (
+  IN UINT16  TimeoutRemain
+  )
+{
+  EFI_GRAPHICS_OUTPUT_BLT_PIXEL_UNION  Black;
+  EFI_GRAPHICS_OUTPUT_BLT_PIXEL_UNION  White;
+  UINT16                               Timeout;
+
+  Timeout = PcdGet16 (PcdPlatformBootTimeOut);
+
+  Black.Raw = 0x00000000;
+  White.Raw = 0x00FFFFFF;
+
+  BootLogoUpdateProgress (
+    White.Pixel,
+    Black.Pixel,
+    L"Start boot option",
+    White.Pixel,
+    (Timeout - TimeoutRemain) * 100 / Timeout,
+    0
+    );
+}
+
+/**
+  The function is called when no boot option could be launched,
+  including platform recovery options and options pointing to applications
+  built into firmware volumes.
+
+  If this function returns, BDS attempts to enter an infinite loop.
+**/
+VOID
+EFIAPI
+PlatformBootManagerUnableToBoot (
+  VOID
+  )
+{
+  EFI_STATUS                    Status;
+  EFI_INPUT_KEY                 Key;
+  EFI_BOOT_MANAGER_LOAD_OPTION  BootManagerMenu;
+  UINTN                         Index;
+
+  //
+  // BootManagerMenu doesn't contain the correct information when return status
+  // is EFI_NOT_FOUND.
+  //
+  Status = EfiBootManagerGetBootManagerMenu (&BootManagerMenu);
+  if (EFI_ERROR (Status)) {
+    return;
+  }
+
+  //
+  // Normally BdsDxe does not print anything to the system console, but this is
+  // a last resort -- the end-user will likely not see any DEBUG messages
+  // logged in this situation.
+  //
+  // AsciiPrint () will NULL-check gST->ConOut internally. We check gST->ConIn
+  // here to see if it makes sense to request and wait for a keypress.
+  //
+  if (gST->ConIn != NULL) {
+    AsciiPrint (
+      "%a: No bootable option or device was found.\n"
+      "%a: Press any key to enter the Boot Manager Menu.\n",
+      gEfiCallerBaseName,
+      gEfiCallerBaseName
+      );
+    Status = gBS->WaitForEvent (1, &gST->ConIn->WaitForKey, &Index);
+    ASSERT_EFI_ERROR (Status);
+    ASSERT (Index == 0);
+
+    //
+    // Drain any queued keys.
+    //
+    while (!EFI_ERROR (gST->ConIn->ReadKeyStroke (gST->ConIn, &Key))) {
+      //
+      // just throw away Key
+      //
+    }
+  }
+
+  for ( ; ; ) {
+    EfiBootManagerBoot (&BootManagerMenu);
+  }
+}
diff --git a/OvmfPkg/LoongArchVirt/Library/PlatformBootManagerLib/PlatformBm.h b/OvmfPkg/LoongArchVirt/Library/PlatformBootManagerLib/PlatformBm.h
new file mode 100644
index 0000000000..140e6b5c23
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/PlatformBootManagerLib/PlatformBm.h
@@ -0,0 +1,112 @@
+/** @file
+  Head file for BDS Platform specific code
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef PLATFORM_BM_H_
+#define PLATFORM_BM_H_
+
+#include <Library/DevicePathLib.h>
+
+#define DP_NODE_LEN(Type)  { (UINT8)sizeof (Type), (UINT8)(sizeof (Type) >> 8) }
+
+#define SERIAL_DXE_FILE_GUID  { \
+          0xD3987D4B, 0x971A, 0x435F, \
+          { 0x8C, 0xAF, 0x49, 0x67, 0xEB, 0x62, 0x72, 0x41 } \
+          }
+
+#define ALIGN_UP(addr, align) \
+    ((addr + (typeof (addr)) align - 1) & ~((typeof (addr)) align - 1))
+
+#pragma pack (1)
+typedef struct {
+  VENDOR_DEVICE_PATH            SerialDxe;
+  UART_DEVICE_PATH              Uart;
+  VENDOR_DEFINED_DEVICE_PATH    TermType;
+  EFI_DEVICE_PATH_PROTOCOL      End;
+} PLATFORM_SERIAL_CONSOLE;
+#pragma pack ()
+
+#pragma pack (1)
+typedef struct {
+  USB_CLASS_DEVICE_PATH       Keyboard;
+  EFI_DEVICE_PATH_PROTOCOL    End;
+} PLATFORM_USB_KEYBOARD;
+#pragma pack ()
+
+/**
+  Check if the handle satisfies a particular condition.
+
+  @param[in] Handle      The handle to check.
+  @param[in] ReportText  A caller-allocated string passed in for reporting
+                         purposes. It must never be NULL.
+
+  @retval TRUE   The condition is satisfied.
+  @retval FALSE  Otherwise. This includes the case when the condition could not
+                 be fully evaluated due to an error.
+**/
+typedef
+BOOLEAN
+(EFIAPI *FILTER_FUNCTION)(
+  IN EFI_HANDLE   Handle,
+  IN CONST CHAR16 *ReportText
+  );
+
+/**
+  Process a handle.
+
+  @param[in] Handle      The handle to process.
+  @param[in] ReportText  A caller-allocated string passed in for reporting
+                         purposes. It must never be NULL.
+**/
+typedef
+VOID
+(EFIAPI *CALLBACK_FUNCTION)(
+  IN EFI_HANDLE   Handle,
+  IN CONST CHAR16 *ReportText
+  );
+
+/**
+ * execute from kernel entry point.
+ *
+ * @param[in] Argc  The count of args.
+ * @param[in] Argv  The pointer to args array.
+ * @param[in] Bpi   The pointer to bootparaminterface struct.
+ * @param[in] Vec   The fourth args for kernel.
+ ***/
+typedef
+VOID
+(EFIAPI *EFI_KERNEL_ENTRY_POINT)(
+  IN UINTN  Argc,
+  IN VOID   *Argv,
+  IN VOID   *Bpi,
+  IN VOID   *Vec
+  );
+
+/**
+  Download the kernel, the initial ramdisk, and the kernel command line from
+  QEMU's fw_cfg. Construct a minimal SimpleFileSystem that contains the two
+  image files, and load and start the kernel from it.
+
+  The kernel will be instructed via its command line to load the initrd from
+  the same Simple FileSystem.
+
+  @retval EFI_NOT_FOUND         Kernel image was not found.
+  @retval EFI_OUT_OF_RESOURCES  Memory allocation failed.
+  @retval EFI_PROTOCOL_ERROR    Unterminated kernel command line.
+
+  @return                       Error codes from any of the underlying
+                                functions. On success, the function doesn't
+                                return.
+**/
+EFI_STATUS
+EFIAPI
+TryRunningQemuKernel (
+  VOID
+  );
+
+#endif // PLATFORM_BM_H_
diff --git a/OvmfPkg/LoongArchVirt/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf b/OvmfPkg/LoongArchVirt/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf
new file mode 100644
index 0000000000..fa4435f519
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf
@@ -0,0 +1,73 @@
+## @file
+#  Implementation for PlatformBootManagerLib library class interfaces.
+#
+#  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = PlatformBootManagerLib
+  FILE_GUID                      = 477E5D8C-DB2E-AB4D-8C2C-6B33DE5CB638
+  MODULE_TYPE                    = DXE_DRIVER
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = PlatformBootManagerLib|DXE_DRIVER
+
+#
+#  VALID_ARCHITECTURES           = LOONGARCH64
+#
+
+[Sources]
+  PlatformBm.c
+  QemuKernel.c
+
+[Packages]
+  MdeModulePkg/MdeModulePkg.dec
+  MdePkg/MdePkg.dec
+  OvmfPkg/OvmfPkg.dec
+  ShellPkg/ShellPkg.dec
+
+[LibraryClasses]
+  BaseLib
+  BaseMemoryLib
+  BootLogoLib
+  DebugLib
+  DevicePathLib
+  MemoryAllocationLib
+  PcdLib
+  PrintLib
+  QemuBootOrderLib
+  QemuLoadImageLib
+  QemuFwCfgLib
+  UefiBootManagerLib
+  UefiBootServicesTableLib
+  UefiLib
+  UefiRuntimeServicesTableLib
+
+[FixedPcd]
+  gEfiMdePkgTokenSpaceGuid.PcdUartDefaultBaudRate
+  gEfiMdePkgTokenSpaceGuid.PcdUartDefaultDataBits
+  gEfiMdePkgTokenSpaceGuid.PcdUartDefaultParity
+  gEfiMdePkgTokenSpaceGuid.PcdUartDefaultStopBits
+
+[Pcd]
+  gEfiMdePkgTokenSpaceGuid.PcdPlatformBootTimeOut
+
+[Guids]
+  gEfiFileInfoGuid
+  gEfiFileSystemInfoGuid
+  gEfiFileSystemVolumeLabelInfoIdGuid
+  gEfiEndOfDxeEventGroupGuid
+  gRootBridgesConnectedEventGroupGuid
+  gUefiShellFileGuid
+  gEfiTtyTermGuid
+
+[Protocols]
+  gEfiDevicePathProtocolGuid
+  gEfiFirmwareVolume2ProtocolGuid
+  gEfiGraphicsOutputProtocolGuid
+  gEfiLoadedImageProtocolGuid
+  gEfiPciRootBridgeIoProtocolGuid
+  gEfiSimpleFileSystemProtocolGuid
diff --git a/OvmfPkg/LoongArchVirt/Library/PlatformBootManagerLib/QemuKernel.c b/OvmfPkg/LoongArchVirt/Library/PlatformBootManagerLib/QemuKernel.c
new file mode 100644
index 0000000000..50489a6fa5
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/PlatformBootManagerLib/QemuKernel.c
@@ -0,0 +1,81 @@
+/** @file
+  Try to run Linux kernel.
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+  @par Glossary:
+    - mem     - Memory
+    - Bpi    - Boot Parameter Interface
+    - FwCfg    - FirmWare Configure
+**/
+
+#include <Library/QemuLoadImageLib.h>
+#include <Library/ReportStatusCodeLib.h>
+
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/DevicePathLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiLib.h>
+#include <Library/UefiRuntimeServicesTableLib.h>
+
+/**
+  Download the kernel, the initial ramdisk, and the kernel command line from
+  QEMU's fw_cfg. Construct a minimal SimpleFileSystem that contains the two
+  image files, and load and start the kernel from it.
+
+  The kernel will be instructed via its command line to load the initrd from
+  the same Simple FileSystem.
+
+  @retval EFI_NOT_FOUND         Kernel image was not found.
+  @retval EFI_OUT_OF_RESOURCES  Memory allocation failed.
+  @retval EFI_PROTOCOL_ERROR    Unterminated kernel command line.
+
+  @return                       Error codes from any of the underlying
+                                functions. On success, the function doesn't
+                                return.
+**/
+EFI_STATUS
+TryRunningQemuKernel (
+  VOID
+  )
+{
+  EFI_STATUS  Status;
+  EFI_HANDLE  KernelImageHandle;
+
+  Status = QemuLoadKernelImage (&KernelImageHandle);
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  //
+  // Signal the EFI_EVENT_GROUP_READY_TO_BOOT event.
+  //
+  EfiSignalEventReadyToBoot ();
+
+  REPORT_STATUS_CODE (
+    EFI_PROGRESS_CODE,
+    (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_DXE_BS_PC_READY_TO_BOOT_EVENT)
+    );
+
+  //
+  // Start the image.
+  //
+  Status = QemuStartKernelImage (&KernelImageHandle);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "%a: QemuStartKernelImage(): %r\n",
+      __FUNCTION__,
+      Status
+      ));
+  }
+
+  QemuUnloadKernelImage (KernelImageHandle);
+
+  return Status;
+}
-- 
2.27.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#110540): https://edk2.groups.io/g/devel/message/110540
Mute This Topic: https://groups.io/mt/102342289/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* [edk2-devel] [PATCH v1 25/29] OvmfPkg/LoongArchVirt: Add FdtQemuFwCfgLib
       [not found] <20231102134249.3983594-1-lichao@loongson.cn>
                   ` (14 preceding siblings ...)
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 24/29] OvmfPkg/LoongArchVirt: Add platform boot manager library Chao Li
@ 2023-11-02 13:42 ` Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 26/29] OvmfPkg/LoongArchVirt: Add reset system library Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 27/29] OvmfPkg/LoongArchVirt: Support SEC phase Chao Li
  17 siblings, 0 replies; 18+ messages in thread
From: Chao Li @ 2023-11-02 13:42 UTC (permalink / raw)
  To: devel
  Cc: Ard Biesheuvel, Jiewen Yao, Jordan Justen, Gerd Hoffmann,
	Xianglai Li, Bibo Mao

This library for PEI phase, and obtains the QemuFwCfg base address by
directly parsing the FDT, reads and writes the data in QemuFwCfg by
operating on the QemuFwCfg base address.

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

Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Chao Li <lichao@loongson.cn>
Co-authored-by: Xianglai Li <lixianglai@loongson.cn>
Co-authored-by: Bibo Mao <maobibo@loongson.cn>
---
 .../FdtQemuFwCfgLib/FdtQemuFwCfgPeiLib.c      | 505 ++++++++++++++++++
 .../FdtQemuFwCfgLib/FdtQemuFwCfgPeiLib.inf    |  42 ++
 .../FdtQemuFwCfgLib/QemuFwCfgLibInternal.h    |  73 +++
 .../Library/FdtQemuFwCfgLib/QemuFwCfgPei.c    | 117 ++++
 4 files changed, 737 insertions(+)
 create mode 100644 OvmfPkg/LoongArchVirt/Library/FdtQemuFwCfgLib/FdtQemuFwCfgPeiLib.c
 create mode 100644 OvmfPkg/LoongArchVirt/Library/FdtQemuFwCfgLib/FdtQemuFwCfgPeiLib.inf
 create mode 100644 OvmfPkg/LoongArchVirt/Library/FdtQemuFwCfgLib/QemuFwCfgLibInternal.h
 create mode 100644 OvmfPkg/LoongArchVirt/Library/FdtQemuFwCfgLib/QemuFwCfgPei.c

diff --git a/OvmfPkg/LoongArchVirt/Library/FdtQemuFwCfgLib/FdtQemuFwCfgPeiLib.c b/OvmfPkg/LoongArchVirt/Library/FdtQemuFwCfgLib/FdtQemuFwCfgPeiLib.c
new file mode 100644
index 0000000000..4009a76a80
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/FdtQemuFwCfgLib/FdtQemuFwCfgPeiLib.c
@@ -0,0 +1,505 @@
+/** @file
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+  @par Glossary:
+    - FwCfg   - firmWare  Configure
+    - CTL   - Control
+**/
+
+#include "Uefi.h"
+#include <Base.h>
+#include <PiPei.h>
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/IoLib.h>
+#include <Library/QemuFwCfgLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Uefi/UefiBaseType.h>
+#include <Library/HobLib.h>
+#include <libfdt.h>
+#include "QemuFwCfgLibInternal.h"
+
+EFI_GUID  mFwCfgSelectorAddressGuid = FW_CONFIG_SELECTOR_ADDRESS_HOB_GUID;
+EFI_GUID  mFwCfgDataAddressGuid     = FW_CONFIG_DATA_ADDRESS_HOB_GUID;
+
+STATIC UINTN  mFwCfgSelectorAddress;
+STATIC UINTN  mFwCfgDataAddress;
+
+/**
+  To get firmware configure selector address.
+
+  @param VOID
+
+  @retval  firmware configure selector address
+**/
+UINTN
+EFIAPI
+QemuGetFwCfgSelectorAddress (
+  VOID
+  )
+{
+  UINTN              FwCfgSelectorAddress;
+  EFI_HOB_GUID_TYPE  *GuidHob;
+  VOID               *DataInHob;
+
+  FwCfgSelectorAddress = mFwCfgSelectorAddress;
+  GuidHob              = NULL;
+  DataInHob            = NULL;
+
+  if (FwCfgSelectorAddress == 0) {
+    GuidHob              = GetFirstGuidHob (&mFwCfgSelectorAddressGuid);
+    DataInHob            = GET_GUID_HOB_DATA (GuidHob);
+    FwCfgSelectorAddress = (UINT64)(*(UINTN *)DataInHob);
+  }
+
+  return FwCfgSelectorAddress;
+}
+
+/**
+  To get firmware configure Data address.
+
+  @param VOID
+
+  @retval  firmware configure data address
+**/
+UINTN
+EFIAPI
+QemuGetFwCfgDataAddress (
+  VOID
+  )
+{
+  UINTN              FwCfgDataAddress;
+  EFI_HOB_GUID_TYPE  *GuidHob;
+  VOID               *DataInHob;
+
+  FwCfgDataAddress = mFwCfgDataAddress;
+  GuidHob          = NULL;
+  DataInHob        = NULL;
+
+  if (FwCfgDataAddress == 0) {
+    GuidHob          = GetFirstGuidHob (&mFwCfgDataAddressGuid);
+    DataInHob        = GET_GUID_HOB_DATA (GuidHob);
+    FwCfgDataAddress = (UINT64)(*(UINTN *)DataInHob);
+  }
+
+  return FwCfgDataAddress;
+}
+
+/**
+  Selects a firmware configuration item for reading.
+
+  Following this call, any data read from this item will start from
+  the beginning of the configuration item's data.
+
+  @param[in] QemuFwCfgItem - Firmware Configuration item to read
+**/
+VOID
+EFIAPI
+QemuFwCfgSelectItem (
+  IN FIRMWARE_CONFIG_ITEM  QemuFwCfgItem
+  )
+{
+  UINTN  FwCfgSelectorAddress;
+
+  FwCfgSelectorAddress = QemuGetFwCfgSelectorAddress ();
+  MmioWrite16 (FwCfgSelectorAddress, SwapBytes16 ((UINT16)(UINTN)QemuFwCfgItem));
+}
+
+/**
+  Slow READ_BYTES_FUNCTION.
+
+  @param[in]  The size of the data to be read.
+  @param[in]  Buffer    The buffer that stores the readout data.
+**/
+VOID
+EFIAPI
+MmioReadBytes (
+  IN UINTN  Size,
+  IN VOID   *Buffer OPTIONAL
+  )
+{
+  UINTN  Left;
+  UINT8  *Ptr;
+  UINT8  *End;
+  UINTN  FwCfgDataAddress;
+
+  Left = Size & 7;
+
+  Size -= Left;
+  Ptr   = Buffer;
+  End   = Ptr + Size;
+
+  FwCfgDataAddress = QemuGetFwCfgDataAddress ();
+  while (Ptr < End) {
+    *(UINT64 *)Ptr = MmioRead64 (FwCfgDataAddress);
+    Ptr           += 8;
+  }
+
+  if (Left & 4) {
+    *(UINT32 *)Ptr = MmioRead32 (FwCfgDataAddress);
+    Ptr           += 4;
+  }
+
+  if (Left & 2) {
+    *(UINT16 *)Ptr = MmioRead16 (FwCfgDataAddress);
+    Ptr           += 2;
+  }
+
+  if (Left & 1) {
+    *Ptr = MmioRead8 (FwCfgDataAddress);
+  }
+}
+
+/**
+  Slow WRITE_BYTES_FUNCTION.
+
+  @param[in]  The size of the data to be write.
+  @param[in]  Buffer    The buffer that stores the writein data.
+**/
+VOID
+EFIAPI
+MmioWriteBytes (
+  IN UINTN  Size,
+  IN VOID   *Buffer OPTIONAL
+  )
+{
+  UINTN  Idx;
+  UINTN  FwCfgDataAddress;
+
+  FwCfgDataAddress = QemuGetFwCfgDataAddress ();
+  for (Idx = 0; Idx < Size; ++Idx) {
+    MmioWrite8 (FwCfgDataAddress, ((UINT8 *)Buffer)[Idx]);
+  }
+}
+
+/**
+  Reads firmware configuration bytes into a buffer
+
+  @param[in] Size - Size in bytes to read
+  @param[in] Buffer - Buffer to store data into  (OPTIONAL if Size is 0)
+**/
+VOID
+EFIAPI
+InternalQemuFwCfgReadBytes (
+  IN UINTN  Size,
+  IN VOID   *Buffer  OPTIONAL
+  )
+{
+  if ((InternalQemuFwCfgDmaIsAvailable ()) &&
+      (Size <= MAX_UINT32))
+  {
+    InternalQemuFwCfgDmaBytes ((UINT32)Size, Buffer, FW_CFG_DMA_CTL_READ);
+    return;
+  }
+
+  MmioReadBytes (Size, Buffer);
+}
+
+/**
+  Reads firmware configuration bytes into a buffer
+
+  If called multiple times, then the data read will
+  continue at the offset of the firmware configuration
+  item where the previous read ended.
+
+  @param[in] Size - Size in bytes to read
+  @param[in] Buffer - Buffer to store data into
+**/
+VOID
+EFIAPI
+QemuFwCfgReadBytes (
+  IN UINTN  Size,
+  IN VOID   *Buffer
+  )
+{
+  if (InternalQemuFwCfgIsAvailable ()) {
+    InternalQemuFwCfgReadBytes (Size, Buffer);
+  } else {
+    ZeroMem (Buffer, Size);
+  }
+}
+
+/**
+  Write firmware configuration bytes from a buffer
+
+  If called multiple times, then the data written will
+  continue at the offset of the firmware configuration
+  item where the previous write ended.
+
+  @param[in] Size - Size in bytes to write
+  @param[in] Buffer - Buffer to read data from
+**/
+VOID
+EFIAPI
+QemuFwCfgWriteBytes (
+  IN UINTN  Size,
+  IN VOID   *Buffer
+  )
+{
+  if (InternalQemuFwCfgIsAvailable ()) {
+    if ((InternalQemuFwCfgDmaIsAvailable ()) &&
+        (Size <= MAX_UINT32))
+    {
+      InternalQemuFwCfgDmaBytes ((UINT32)Size, Buffer, FW_CFG_DMA_CTL_WRITE);
+      return;
+    }
+
+    MmioWriteBytes (Size, Buffer);
+  }
+}
+
+/**
+  Skip bytes in the firmware configuration item.
+
+  Increase the offset of the firmware configuration item without transferring
+  bytes between the item and a caller-provided buffer. Subsequent read, write
+  or skip operations will commence at the increased offset.
+
+  @param[in] Size  Number of bytes to skip.
+**/
+VOID
+EFIAPI
+QemuFwCfgSkipBytes (
+  IN UINTN  Size
+  )
+{
+  UINTN  ChunkSize;
+  UINT8  SkipBuffer[256];
+
+  if (!InternalQemuFwCfgIsAvailable ()) {
+    return;
+  }
+
+  if ((InternalQemuFwCfgDmaIsAvailable ()) &&
+      (Size <= MAX_UINT32))
+  {
+    InternalQemuFwCfgDmaBytes ((UINT32)Size, NULL, FW_CFG_DMA_CTL_SKIP);
+    return;
+  }
+
+  //
+  // Emulate the skip by reading data in chunks, and throwing it away. The
+  // implementation below is suitable even for phases where RAM or dynamic
+  // allocation is not available or appropriate. It also doesn't affect the
+  // static data footprint for client modules. Large skips are not expected,
+  // therefore this fallback is not performance critical. The size of
+  // SkipBuffer is thought not to exert a large pressure on the stack in any
+  // phase.
+  //
+  while (Size > 0) {
+    ChunkSize = MIN (Size, sizeof SkipBuffer);
+    MmioReadBytes (ChunkSize, SkipBuffer);
+    Size -= ChunkSize;
+  }
+}
+
+/**
+  Reads a UINT8 firmware configuration value
+
+  @return    Value of Firmware Configuration item read
+**/
+UINT8
+EFIAPI
+QemuFwCfgRead8 (
+  VOID
+  )
+{
+  UINT8  Result;
+
+  QemuFwCfgReadBytes (sizeof (Result), &Result);
+
+  return Result;
+}
+
+/**
+  Reads a UINT16 firmware configuration value
+
+  @return    Value of Firmware Configuration item read
+**/
+UINT16
+EFIAPI
+QemuFwCfgRead16 (
+  VOID
+  )
+{
+  UINT16  Result;
+
+  QemuFwCfgReadBytes (sizeof (Result), &Result);
+
+  return Result;
+}
+
+/**
+  Reads a UINT32 firmware configuration value
+
+  @return    Value of Firmware Configuration item read
+**/
+UINT32
+EFIAPI
+QemuFwCfgRead32 (
+  VOID
+  )
+{
+  UINT32  Result;
+
+  QemuFwCfgReadBytes (sizeof (Result), &Result);
+
+  return Result;
+}
+
+/**
+  Reads a UINT64 firmware configuration value
+
+  @return    Value of Firmware Configuration item read
+**/
+UINT64
+EFIAPI
+QemuFwCfgRead64 (
+  VOID
+  )
+{
+  UINT64  Result;
+
+  QemuFwCfgReadBytes (sizeof (Result), &Result);
+
+  return Result;
+}
+
+/**
+  Find the configuration item corresponding to the firmware configuration file.
+
+  @param[in]  Name - Name of file to look up.
+  @param[out] Item - Configuration item corresponding to the file, to be passed
+                     to QemuFwCfgSelectItem ().
+  @param[out] Size - Number of bytes in the file.
+
+  @return    RETURN_SUCCESS       If file is found.
+             RETURN_NOT_FOUND     If file is not found.
+             RETURN_UNSUPPORTED   If firmware configuration is unavailable.
+**/
+RETURN_STATUS
+EFIAPI
+QemuFwCfgFindFile (
+  IN   CONST CHAR8           *Name,
+  OUT  FIRMWARE_CONFIG_ITEM  *Item,
+  OUT  UINTN                 *Size
+  )
+{
+  UINT32  Count;
+  UINT32  Idx;
+
+  if (!InternalQemuFwCfgIsAvailable ()) {
+    return RETURN_UNSUPPORTED;
+  }
+
+  QemuFwCfgSelectItem (QemuFwCfgItemFileDir);
+  Count = SwapBytes32 (QemuFwCfgRead32 ());
+
+  for (Idx = 0; Idx < Count; ++Idx) {
+    UINT32  FileSize;
+    UINT16  FileSelect;
+    CHAR8   FileName[QEMU_FW_CFG_FNAME_SIZE];
+
+    FileSize   = QemuFwCfgRead32 ();
+    FileSelect = QemuFwCfgRead16 ();
+    QemuFwCfgRead16 (); // skip the field called "reserved"
+    InternalQemuFwCfgReadBytes (sizeof (FileName), FileName);
+
+    if (AsciiStrCmp (Name, FileName) == 0) {
+      *Item = SwapBytes16 (FileSelect);
+      *Size = SwapBytes32 (FileSize);
+      return RETURN_SUCCESS;
+    }
+  }
+
+  return RETURN_NOT_FOUND;
+}
+
+/**
+  firmware config initialize.
+
+  @param  VOID
+
+  @return    RETURN_SUCCESS  Initialization succeeded.
+**/
+RETURN_STATUS
+EFIAPI
+FdtQemuFwCfgInitialize (
+  VOID
+  )
+{
+  VOID          *DeviceTreeBase;
+  INT32         Node;
+  INT32         Prev;
+  CONST CHAR8   *Type;
+  INT32         Len;
+  CONST UINT64  *RegProp;
+  UINT64        FwCfgSelectorAddress;
+  UINT64        FwCfgDataAddress;
+  UINT64        FwCfgDataSize;
+
+  DeviceTreeBase = (VOID *)(UINTN)PcdGet64 (PcdDeviceTreeInitialBaseAddress);
+  ASSERT (DeviceTreeBase != NULL);
+  //
+  // Make sure we have a valid device tree blob
+  //
+  ASSERT (fdt_check_header (DeviceTreeBase) == 0);
+
+  for (Prev = 0; ; Prev = Node) {
+    Node = fdt_next_node (DeviceTreeBase, Prev, NULL);
+    if (Node < 0) {
+      break;
+    }
+
+    //
+    // Check for memory node
+    //
+    Type = fdt_getprop (DeviceTreeBase, Node, "compatible", &Len);
+    if ((Type) &&
+        (AsciiStrnCmp (Type, "qemu,fw-cfg-mmio", Len) == 0))
+    {
+      //
+      // Get the 'reg' property of this node. For now, we will assume
+      // two 8 byte quantities for base and size, respectively.
+      //
+      RegProp = fdt_getprop (DeviceTreeBase, Node, "reg", &Len);
+      if ((RegProp != 0) &&
+          (Len == (2 * sizeof (UINT64))))
+      {
+        FwCfgDataAddress     = SwapBytes64 (RegProp[0]);
+        FwCfgDataSize        = 8;
+        FwCfgSelectorAddress = FwCfgDataAddress + FwCfgDataSize;
+
+        mFwCfgSelectorAddress = FwCfgSelectorAddress;
+        mFwCfgDataAddress     = FwCfgDataAddress;
+
+        BuildGuidDataHob (
+          &mFwCfgSelectorAddressGuid,
+          (VOID *)&FwCfgSelectorAddress,
+          sizeof (UINT64)
+          );
+
+        BuildGuidDataHob (
+          &mFwCfgDataAddressGuid,
+          (VOID *)&FwCfgDataAddress,
+          sizeof (UINT64)
+          );
+        break;
+      } else {
+        DEBUG ((
+          DEBUG_ERROR,
+          "%a: Failed to parse FDT QemuCfg node\n",
+          __FUNCTION__
+          ));
+        break;
+      }
+    }
+  }
+
+  return RETURN_SUCCESS;
+}
diff --git a/OvmfPkg/LoongArchVirt/Library/FdtQemuFwCfgLib/FdtQemuFwCfgPeiLib.inf b/OvmfPkg/LoongArchVirt/Library/FdtQemuFwCfgLib/FdtQemuFwCfgPeiLib.inf
new file mode 100644
index 0000000000..4c9d4bcd81
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/FdtQemuFwCfgLib/FdtQemuFwCfgPeiLib.inf
@@ -0,0 +1,42 @@
+## @file
+#  initialized fw_cfg library.
+#
+#  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = FdtQemuFwCfgPeiLib
+  FILE_GUID                      = cdf9a9d5-7422-4dcb-b41d-607151ad320b
+  MODULE_TYPE                    = BASE
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = FtdQemuFwCfgLib|PEIM
+  CONSTRUCTOR                    = FdtQemuFwCfgInitialize
+
+#
+#  VALID_ARCHITECTURES           = LOONGARCH64
+#
+
+[Sources]
+  FdtQemuFwCfgPeiLib.c
+  QemuFwCfgPei.c
+
+[Packages]
+  EmbeddedPkg/EmbeddedPkg.dec
+  MdePkg/MdePkg.dec
+  OvmfPkg/OvmfPkg.dec
+
+[LibraryClasses]
+  BaseLib
+  BaseMemoryLib
+  HobLib
+  DebugLib
+  IoLib
+  MemoryAllocationLib
+  FdtLib
+
+[Pcd]
+  gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress
diff --git a/OvmfPkg/LoongArchVirt/Library/FdtQemuFwCfgLib/QemuFwCfgLibInternal.h b/OvmfPkg/LoongArchVirt/Library/FdtQemuFwCfgLib/QemuFwCfgLibInternal.h
new file mode 100644
index 0000000000..17866cb9d5
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/FdtQemuFwCfgLib/QemuFwCfgLibInternal.h
@@ -0,0 +1,73 @@
+/** @file
+  fw_cfg library implementation.
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+  @par Glossary:
+    - FwCfg   - firmWare  Configure
+**/
+
+#ifndef QEMU_FW_CFG_LIB_INTERNAL_H_
+#define QEMU_FW_CFG_LIB_INTERNAL_H_
+
+#define FW_CONFIG_SELECTOR_ADDRESS_HOB_GUID \
+  { \
+    0x3cc47b04, 0x0d3e, 0xaa64, { 0x06, 0xa6, 0x4b, 0xdc, 0x9a, 0x2c, 0x61, 0x19 } \
+  }
+
+#define FW_CONFIG_DATA_ADDRESS_HOB_GUID \
+  { \
+    0xef854788, 0x10f3, 0x8e7a, { 0x3e, 0xd0, 0x4d, 0x16, 0xc1, 0x79, 0x55, 0x2f } \
+  }
+
+/**
+  Returns a boolean indicating if the firmware configuration interface is
+  available for library-internal purposes.
+
+  This function never changes fw_cfg state.
+
+  @retval    TRUE   The interface is available internally.
+  @retval    FALSE  The interface is not available internally.
+**/
+BOOLEAN
+InternalQemuFwCfgIsAvailable (
+  VOID
+  );
+
+/**
+  Returns a boolean indicating whether QEMU provides the DMA-like access method
+  for fw_cfg.
+
+  @retval    TRUE   The DMA-like access method is available.
+  @retval    FALSE  The DMA-like access method is unavailable.
+**/
+BOOLEAN
+InternalQemuFwCfgDmaIsAvailable (
+  VOID
+  );
+
+/**
+  Transfer an array of bytes, or skip a number of bytes, using the DMA
+  interface.
+
+  @param[in]     Size     Size in bytes to transfer or skip.
+
+  @param[in,out] Buffer   Buffer to read data into or write data from. Ignored,
+                          and may be NULL, if Size is zero, or Control is
+                          FW_CFG_DMA_CTL_SKIP.
+
+  @param[in]     Control  One of the following:
+                          FW_CFG_DMA_CTL_WRITE - write to fw_cfg from Buffer.
+                          FW_CFG_DMA_CTL_READ  - read from fw_cfg into Buffer.
+                          FW_CFG_DMA_CTL_SKIP  - skip bytes in fw_cfg.
+**/
+VOID
+InternalQemuFwCfgDmaBytes (
+  IN     UINT32  Size,
+  IN OUT VOID    *Buffer OPTIONAL,
+  IN     UINT32  Control
+  );
+
+#endif // QEMU_FW_CFG_LIB_INTERNAL_H_
diff --git a/OvmfPkg/LoongArchVirt/Library/FdtQemuFwCfgLib/QemuFwCfgPei.c b/OvmfPkg/LoongArchVirt/Library/FdtQemuFwCfgLib/QemuFwCfgPei.c
new file mode 100644
index 0000000000..07dc3d1c23
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/FdtQemuFwCfgLib/QemuFwCfgPei.c
@@ -0,0 +1,117 @@
+/** @file
+  fw_cfg library implementation.
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+  @par Glossary:
+    - FwCfg   - firmWare  Configure
+**/
+
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/QemuFwCfgLib.h>
+
+#include "QemuFwCfgLibInternal.h"
+
+/**
+  Returns a boolean indicating if the firmware configuration interface
+  is available or not.
+
+  This function may change fw_cfg state.
+
+  @retval    TRUE   The interface is available
+  @retval    FALSE  The interface is not available
+**/
+BOOLEAN
+EFIAPI
+QemuFwCfgIsAvailable (
+  VOID
+  )
+{
+  UINT32  Signature;
+  UINT32  Revision;
+
+  QemuFwCfgSelectItem (QemuFwCfgItemSignature);
+  Signature = QemuFwCfgRead32 ();
+  DEBUG ((DEBUG_INFO, "FW CFG Signature: 0x%x\n", Signature));
+  QemuFwCfgSelectItem (QemuFwCfgItemInterfaceVersion);
+  Revision = QemuFwCfgRead32 ();
+  DEBUG ((DEBUG_INFO, "FW CFG Revision: 0x%x\n", Revision));
+  if ((Signature != SIGNATURE_32 ('Q', 'E', 'M', 'U')) ||
+      (Revision < 1))
+  {
+    DEBUG ((DEBUG_INFO, "QemuFwCfg interface not supported.\n"));
+    return FALSE;
+  }
+
+  DEBUG ((DEBUG_INFO, "QemuFwCfg interface is supported.\n"));
+  return TRUE;
+}
+
+/**
+  Returns a boolean indicating if the firmware configuration interface is
+  available for library-internal purposes.
+
+  This function never changes fw_cfg state.
+
+  @retval    TRUE   The interface is available internally.
+  @retval    FALSE  The interface is not available internally.
+**/
+BOOLEAN
+InternalQemuFwCfgIsAvailable (
+  VOID
+  )
+{
+  //
+  // We always return TRUE, because the consumer of this library ought to have
+  // called QemuFwCfgIsAvailable before making other calls which would hit this
+  // path.
+  //
+  return TRUE;
+}
+
+/**
+  Returns a boolean indicating whether QEMU provides the DMA-like access method
+  for fw_cfg.
+
+  @retval    TRUE   The DMA-like access method is available.
+  @retval    FALSE  The DMA-like access method is unavailable.
+**/
+BOOLEAN
+InternalQemuFwCfgDmaIsAvailable (
+  VOID
+  )
+{
+  return FALSE;
+}
+
+/**
+  Transfer an array of bytes, or skip a number of bytes, using the DMA
+  interface.
+
+  @param[in]     Size     Size in bytes to transfer or skip.
+
+  @param[in, out] Buffer   Buffer to read data into or write data from. Ignored,
+                          and may be NULL, if Size is zero, or Control is
+                          FW_CFG_DMA_CTL_SKIP.
+
+  @param[in]     Control  One of the following:
+                          FW_CFG_DMA_CTL_WRITE - write to fw_cfg from Buffer.
+                          FW_CFG_DMA_CTL_READ  - read from fw_cfg into Buffer.
+                          FW_CFG_DMA_CTL_SKIP  - skip bytes in fw_cfg.
+**/
+VOID
+InternalQemuFwCfgDmaBytes (
+  IN     UINT32  Size,
+  IN OUT VOID    *Buffer OPTIONAL,
+  IN     UINT32  Control
+  )
+{
+  //
+  // We should never reach here
+  //
+  ASSERT (FALSE);
+  CpuDeadLoop ();
+}
-- 
2.27.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#110542): https://edk2.groups.io/g/devel/message/110542
Mute This Topic: https://groups.io/mt/102342334/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* [edk2-devel] [PATCH v1 26/29] OvmfPkg/LoongArchVirt: Add reset system library
       [not found] <20231102134249.3983594-1-lichao@loongson.cn>
                   ` (15 preceding siblings ...)
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 25/29] OvmfPkg/LoongArchVirt: Add FdtQemuFwCfgLib Chao Li
@ 2023-11-02 13:42 ` Chao Li
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 27/29] OvmfPkg/LoongArchVirt: Support SEC phase Chao Li
  17 siblings, 0 replies; 18+ messages in thread
From: Chao Li @ 2023-11-02 13:42 UTC (permalink / raw)
  To: devel
  Cc: Ard Biesheuvel, Jiewen Yao, Jordan Justen, Gerd Hoffmann,
	Xianglai Li, Bibo Mao

This library provides interface related to restart and shudown the
LoongArch64 virtual machine.

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

Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Chao Li <lichao@loongson.cn>
Co-authored-by: Xianglai Li <lixianglai@loongson.cn>
Co-authored-by: Bibo Mao <maobibo@loongson.cn>
---
 .../BaseResetSystemAcpiGed.c                  | 148 ++++++++++
 .../BaseResetSystemAcpiGedLib.inf             |  37 +++
 .../DxeResetSystemAcpiGed.c                   | 259 ++++++++++++++++++
 .../DxeResetSystemAcpiGedLib.inf              |  41 +++
 .../ResetSystemAcpiLib/ResetSystemAcpiGed.c   | 128 +++++++++
 .../ResetSystemAcpiLib/ResetSystemAcpiGed.h   |  23 ++
 6 files changed, 636 insertions(+)
 create mode 100644 OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/BaseResetSystemAcpiGed.c
 create mode 100644 OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/BaseResetSystemAcpiGedLib.inf
 create mode 100644 OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/DxeResetSystemAcpiGed.c
 create mode 100644 OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/DxeResetSystemAcpiGedLib.inf
 create mode 100644 OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/ResetSystemAcpiGed.c
 create mode 100644 OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/ResetSystemAcpiGed.h

diff --git a/OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/BaseResetSystemAcpiGed.c b/OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/BaseResetSystemAcpiGed.c
new file mode 100644
index 0000000000..adb66f365a
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/BaseResetSystemAcpiGed.c
@@ -0,0 +1,148 @@
+/** @file
+  Base ResetSystem library implementation.
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Base.h>
+#include <Library/DebugLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include "ResetSystemAcpiGed.h"
+#include <Library/QemuFwCfgLib.h>
+
+/**
+  Get configuration item data by the firmware configuration file name.
+
+  @param[in]  Name - Name of file to look up.
+
+  @return    VOID*       The Pointer of Value of Firmware Configuration item read.
+**/
+VOID *
+GetFwCfgData (
+  CONST CHAR8  *Name
+  )
+{
+  FIRMWARE_CONFIG_ITEM  FwCfgItem;
+  EFI_STATUS            Status;
+  UINTN                 FwCfgSize;
+  VOID                  *Data;
+
+  Status = QemuFwCfgFindFile (Name, &FwCfgItem, &FwCfgSize);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_ERROR, "%a %d read  %s error Status %d \n", __func__, __LINE__, Name, Status));
+    return NULL;
+  }
+
+  Data = AllocatePool (FwCfgSize);
+  if (Data == NULL) {
+    return NULL;
+  }
+
+  QemuFwCfgSelectItem (FwCfgItem);
+  QemuFwCfgReadBytes (FwCfgSize, Data);
+
+  return Data;
+}
+
+/**
+  Find the power manager related info from ACPI table
+
+  @retval RETURN_SUCCESS     Successfully find out all the required information.
+  @retval RETURN_NOT_FOUND   Failed to find the required info.
+**/
+STATIC EFI_STATUS
+GetPowerManagerByParseAcpiInfo (
+  VOID
+  )
+{
+  EFI_ACPI_5_0_FIXED_ACPI_DESCRIPTION_TABLE     *Fadt       = NULL;
+  EFI_ACPI_3_0_ROOT_SYSTEM_DESCRIPTION_POINTER  *Rsdp       = NULL;
+  EFI_ACPI_DESCRIPTION_HEADER                   *Xsdt       = NULL;
+  EFI_ACPI_DESCRIPTION_HEADER                   *Rsdt       = NULL;
+  VOID                                          *AcpiTables = NULL;
+  UINT32                                        *Entry32    = NULL;
+  UINTN                                         Entry32Num;
+  UINT32                                        *Signature = NULL;
+  UINTN                                         Idx;
+
+  Rsdp = GetFwCfgData ("etc/acpi/rsdp");
+  if (Rsdp == NULL) {
+    DEBUG ((DEBUG_ERROR, "%a %d read etc/acpi/rsdp error \n", __func__, __LINE__));
+    return RETURN_NOT_FOUND;
+  }
+
+  AcpiTables = GetFwCfgData ("etc/acpi/tables");
+  if (AcpiTables == NULL) {
+    DEBUG ((DEBUG_ERROR, "%a %d read etc/acpi/tables error \n", __func__, __LINE__));
+    FreePool (Rsdp);
+    return RETURN_NOT_FOUND;
+  }
+
+  Rsdt       = (EFI_ACPI_DESCRIPTION_HEADER *)((UINTN)AcpiTables +  Rsdp->RsdtAddress);
+  Entry32    = (UINT32 *)(Rsdt + 1);
+  Entry32Num = (Rsdt->Length - sizeof (EFI_ACPI_DESCRIPTION_HEADER)) >> 2;
+  for (Idx = 0; Idx < Entry32Num; Idx++) {
+    Signature = (UINT32 *)((UINTN)Entry32[Idx] + (UINTN)AcpiTables);
+    if (*Signature == EFI_ACPI_5_0_FIXED_ACPI_DESCRIPTION_TABLE_SIGNATURE) {
+      Fadt = (EFI_ACPI_5_0_FIXED_ACPI_DESCRIPTION_TABLE *)Signature;
+      DEBUG ((DEBUG_INFO, "Found Fadt in Rsdt\n"));
+      goto Done;
+    }
+  }
+
+  Xsdt       = (EFI_ACPI_DESCRIPTION_HEADER *)((UINTN)AcpiTables +  Rsdp->XsdtAddress);
+  Entry32    = (UINT32 *)(Xsdt + 1);
+  Entry32Num = (Xsdt->Length - sizeof (EFI_ACPI_DESCRIPTION_HEADER)) >> 2;
+  for (Idx = 0; Idx < Entry32Num; Idx++) {
+    Signature = (UINT32 *)((UINTN)Entry32[Idx] + (UINTN)AcpiTables);
+    if (*Signature == EFI_ACPI_5_0_FIXED_ACPI_DESCRIPTION_TABLE_SIGNATURE) {
+      Fadt = (EFI_ACPI_5_0_FIXED_ACPI_DESCRIPTION_TABLE *)Signature;
+      DEBUG ((DEBUG_INFO, "Found Fadt in Xsdt\n"));
+      goto Done;
+    }
+  }
+
+  FreePool (Rsdp);
+  FreePool (AcpiTables);
+  DEBUG ((DEBUG_ERROR, " Fadt Not Found\n"));
+  return RETURN_NOT_FOUND;
+
+Done:
+  mPowerManager.ResetRegAddr        = Fadt->ResetReg.Address;
+  mPowerManager.ResetValue          = Fadt->ResetValue;
+  mPowerManager.SleepControlRegAddr = Fadt->SleepControlReg.Address;
+  mPowerManager.SleepStatusRegAddr  = Fadt->SleepStatusReg.Address;
+
+  FreePool (Rsdp);
+  FreePool (AcpiTables);
+  return RETURN_SUCCESS;
+}
+
+/**
+  The constructor function to initialize mPowerManager.
+
+  @retval EFI_SUCCESS   initialize mPowerManager success.
+  @retval RETURN_NOT_FOUND   Failed to initialize mPowerManager.
+**/
+EFI_STATUS
+ResetSystemLibConstructor (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  )
+{
+  EFI_STATUS  Status;
+
+  Status = GetPowerManagerByParseAcpiInfo ();
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_INFO, "%a:%d\n", __FUNCTION__, __LINE__));
+  }
+
+  ASSERT (mPowerManager.SleepControlRegAddr);
+  ASSERT (mPowerManager.SleepStatusRegAddr);
+  ASSERT (mPowerManager.ResetRegAddr);
+  return Status;
+}
diff --git a/OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/BaseResetSystemAcpiGedLib.inf b/OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/BaseResetSystemAcpiGedLib.inf
new file mode 100644
index 0000000000..7027a688ee
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/BaseResetSystemAcpiGedLib.inf
@@ -0,0 +1,37 @@
+## @file
+#  Base library instance for ResetSystem library class for LoongArch
+#
+#  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+  INF_VERSION                    = 1.29
+  BASE_NAME                      = ResetSystemLib
+  FILE_GUID                      = BA521997-9016-32B5-65DF-EA5F560A3837
+  MODULE_TYPE                    = BASE
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = ResetSystemLib|SEC PEI_CORE PEIM DXE_CORE
+  CONSTRUCTOR                    = ResetSystemLibConstructor
+
+#
+#  VALID_ARCHITECTURES           = LOONGARCH64
+#
+
+[Sources]
+  BaseResetSystemAcpiGed.c
+  ResetSystemAcpiGed.c
+
+[Packages]
+  MdeModulePkg/MdeModulePkg.dec
+  MdePkg/MdePkg.dec
+  OvmfPkg/OvmfPkg.dec
+
+[LibraryClasses]
+  BaseLib
+  DebugLib
+  QemuFwCfgLib
+  MemoryAllocationLib
+  IoLib
diff --git a/OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/DxeResetSystemAcpiGed.c b/OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/DxeResetSystemAcpiGed.c
new file mode 100644
index 0000000000..3fbb4046b5
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/DxeResetSystemAcpiGed.c
@@ -0,0 +1,259 @@
+/** @file
+  Dxe ResetSystem library implementation.
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Base.h>
+#include <Library/DebugLib.h>
+#include <Library/UefiRuntimeLib.h> // EfiConvertPointer()
+#include <Library/DxeServicesTableLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include "ResetSystemAcpiGed.h"
+#include <Library/UefiLib.h>
+
+/**
+  Modifies the attributes to Runtime type for a page size memory region.
+
+  @param  BaseAddress            Specified start address
+
+  @retval EFI_SUCCESS           The attributes were set for the memory region.
+  @retval EFI_INVALID_PARAMETER Length is zero.
+  @retval EFI_UNSUPPORTED       The processor does not support one or more bytes of the memory
+                                resource range specified by BaseAddress and Length.
+  @retval EFI_UNSUPPORTED       The bit mask of attributes is not support for the memory resource
+                                range specified by BaseAddress and Length.
+  @retval EFI_ACCESS_DEFINED    The attributes for the memory resource range specified by
+                                BaseAddress and Length cannot be modified.
+  @retval EFI_OUT_OF_RESOURCES  There are not enough system resources to modify the attributes of
+                                the memory resource range.
+  @retval EFI_NOT_AVAILABLE_YET The attributes cannot be set because CPU architectural protocol is
+                                not available yet.
+**/
+EFI_STATUS
+SetMemoryAttributesRunTime (
+  UINTN  Address
+  )
+{
+  EFI_STATUS                       Status;
+  EFI_GCD_MEMORY_SPACE_DESCRIPTOR  Descriptor;
+
+  Address &= ~EFI_PAGE_MASK;
+
+  Status = gDS->GetMemorySpaceDescriptor (Address, &Descriptor);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_INFO, "%a: GetMemorySpaceDescriptor failed\n", __FUNCTION__));
+    return Status;
+  }
+
+  if (Descriptor.GcdMemoryType == EfiGcdMemoryTypeNonExistent) {
+    Status = gDS->AddMemorySpace (
+                    EfiGcdMemoryTypeMemoryMappedIo,
+                    Address,
+                    EFI_PAGE_SIZE,
+                    EFI_MEMORY_UC | EFI_MEMORY_RUNTIME
+                    );
+    if (EFI_ERROR (Status)) {
+      DEBUG ((DEBUG_INFO, "%a: AddMemorySpace failed\n", __FUNCTION__));
+      return Status;
+    }
+
+    Status = gDS->SetMemorySpaceAttributes (
+                    Address,
+                    EFI_PAGE_SIZE,
+                    EFI_MEMORY_RUNTIME
+                    );
+    if (EFI_ERROR (Status)) {
+      DEBUG ((DEBUG_INFO, "%a:%d SetMemorySpaceAttributes failed\n", __FUNCTION__, __LINE__));
+      return Status;
+    }
+  } else if (!(Descriptor.Attributes & EFI_MEMORY_RUNTIME)) {
+    Status = gDS->SetMemorySpaceAttributes (
+                    Address,
+                    EFI_PAGE_SIZE,
+                    Descriptor.Attributes | EFI_MEMORY_RUNTIME
+                    );
+
+    if (EFI_ERROR (Status)) {
+      DEBUG ((DEBUG_INFO, "%a:%d SetMemorySpaceAttributes failed\n", __FUNCTION__, __LINE__));
+      return Status;
+    }
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Find the power manager related info from ACPI table
+
+  @retval RETURN_SUCCESS     Successfully find out all the required information.
+  @retval RETURN_NOT_FOUND   Failed to find the required info.
+**/
+STATIC EFI_STATUS
+GetPowerManagerByParseAcpiInfo (
+  VOID
+  )
+{
+  EFI_ACPI_5_0_FIXED_ACPI_DESCRIPTION_TABLE     *Fadt    = NULL;
+  EFI_ACPI_3_0_ROOT_SYSTEM_DESCRIPTION_POINTER  *Rsdp    = NULL;
+  EFI_ACPI_DESCRIPTION_HEADER                   *Xsdt    = NULL;
+  EFI_ACPI_DESCRIPTION_HEADER                   *Rsdt    = NULL;
+  UINT32                                        *Entry32 = NULL;
+  UINTN                                         Entry32Num;
+  UINT32                                        *Signature = NULL;
+  UINTN                                         Idx;
+  EFI_STATUS                                    Status;
+
+  Status = EfiGetSystemConfigurationTable (&gEfiAcpiTableGuid, (VOID **)&Rsdp);
+  if (EFI_ERROR (Status)) {
+    Status = EfiGetSystemConfigurationTable (&gEfiAcpi10TableGuid, (VOID **)&Rsdp);
+  }
+
+  if (EFI_ERROR (Status) || (Rsdp == NULL)) {
+    DEBUG ((DEBUG_ERROR, "EFI_ERROR or Rsdp == NULL\n"));
+    return RETURN_NOT_FOUND;
+  }
+
+  Rsdt       = (EFI_ACPI_DESCRIPTION_HEADER *)(UINTN)Rsdp->RsdtAddress;
+  Entry32    = (UINT32 *)(UINTN)(Rsdt + 1);
+  Entry32Num = (Rsdt->Length - sizeof (EFI_ACPI_DESCRIPTION_HEADER)) >> 2;
+  for (Idx = 0; Idx < Entry32Num; Idx++) {
+    Signature = (UINT32 *)(UINTN)Entry32[Idx];
+    if (*Signature == EFI_ACPI_5_0_FIXED_ACPI_DESCRIPTION_TABLE_SIGNATURE) {
+      Fadt = (EFI_ACPI_5_0_FIXED_ACPI_DESCRIPTION_TABLE *)Signature;
+      DEBUG ((DEBUG_INFO, "Found Fadt in Rsdt\n"));
+      goto Done;
+    }
+  }
+
+  Xsdt       = (EFI_ACPI_DESCRIPTION_HEADER *)Rsdp->XsdtAddress;
+  Entry32    = (UINT32 *)(Xsdt + 1);
+  Entry32Num = (Xsdt->Length - sizeof (EFI_ACPI_DESCRIPTION_HEADER)) >> 2;
+  for (Idx = 0; Idx < Entry32Num; Idx++) {
+    Signature = (UINT32 *)(UINTN)Entry32[Idx];
+    if (*Signature == EFI_ACPI_5_0_FIXED_ACPI_DESCRIPTION_TABLE_SIGNATURE) {
+      Fadt = (EFI_ACPI_5_0_FIXED_ACPI_DESCRIPTION_TABLE *)Signature;
+      DEBUG ((DEBUG_INFO, "Found Fadt in Xsdt\n"));
+      goto Done;
+    }
+  }
+
+  DEBUG ((DEBUG_ERROR, " Fadt Not Found\n"));
+  return RETURN_NOT_FOUND;
+
+Done:
+  mPowerManager.ResetRegAddr        = Fadt->ResetReg.Address;
+  mPowerManager.ResetValue          = Fadt->ResetValue;
+  mPowerManager.SleepControlRegAddr = Fadt->SleepControlReg.Address;
+  mPowerManager.SleepStatusRegAddr  = Fadt->SleepStatusReg.Address;
+  return RETURN_SUCCESS;
+}
+
+/**
+  This is a notification function registered on EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE
+  event. It converts a pointer to a new virtual address.
+
+  @param[in] Event        Event whose notification function is being invoked.
+  @param[in] Context      Pointer to the notification function's context
+**/
+VOID
+EFIAPI
+ResetSystemLibAddressChangeEvent (
+  IN EFI_EVENT  Event,
+  IN VOID       *Context
+  )
+{
+  EfiConvertPointer (0, (VOID **)&mPowerManager.SleepControlRegAddr);
+  EfiConvertPointer (0, (VOID **)&mPowerManager.SleepStatusRegAddr);
+  EfiConvertPointer (0, (VOID **)&mPowerManager.ResetRegAddr);
+}
+
+/**
+  Notification function of ACPI Table change.
+
+  This is a notification function registered on ACPI Table change event.
+  It saves the Century address stored in ACPI FADT table.
+
+  @param  Event        Event whose notification function is being invoked.
+  @param  Context      Pointer to the notification function's context.
+**/
+STATIC VOID
+AcpiNotificationEvent (
+  IN EFI_EVENT  Event,
+  IN VOID       *Context
+  )
+{
+  EFI_STATUS  Status;
+
+  Status = GetPowerManagerByParseAcpiInfo ();
+  if (EFI_ERROR (Status)) {
+    return;
+  }
+
+  DEBUG ((DEBUG_INFO, "%a: sleepControl %llx\n", __FUNCTION__, mPowerManager.SleepControlRegAddr));
+  ASSERT (mPowerManager.SleepControlRegAddr);
+  Status =  SetMemoryAttributesRunTime (mPowerManager.SleepControlRegAddr);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_INFO, "%a:%d\n", __FUNCTION__, __LINE__));
+    return;
+  }
+
+  DEBUG ((DEBUG_INFO, "%a: sleepStatus %llx\n", __FUNCTION__, mPowerManager.SleepStatusRegAddr));
+  ASSERT (mPowerManager.SleepStatusRegAddr);
+  Status =  SetMemoryAttributesRunTime (mPowerManager.SleepStatusRegAddr);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_INFO, "%a:%d\n", __FUNCTION__, __LINE__));
+    return;
+  }
+
+  DEBUG ((DEBUG_INFO, "%a: ResetReg %llx\n", __FUNCTION__, mPowerManager.ResetRegAddr));
+  ASSERT (mPowerManager.ResetRegAddr);
+  Status =  SetMemoryAttributesRunTime (mPowerManager.ResetRegAddr);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_INFO, "%a:%d\n", __FUNCTION__, __LINE__));
+  }
+
+  return;
+}
+
+/**
+  The constructor function to Register ACPI Table change event and Address Change Event.
+
+  @retval EFI_SUCCESS   The constructor always returns RETURN_SUCCESS.
+**/
+EFI_STATUS
+EFIAPI
+ResetSystemLibConstructor (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  )
+{
+  EFI_STATUS  Status;
+  EFI_EVENT   Event;
+  EFI_EVENT   ResetSystemVirtualNotifyEvent;
+
+  Status = gBS->CreateEventEx (
+                  EVT_NOTIFY_SIGNAL,
+                  TPL_CALLBACK,
+                  AcpiNotificationEvent,
+                  NULL,
+                  &gEfiAcpiTableGuid,
+                  &Event
+                  );
+
+  //
+  // Register SetVirtualAddressMap () notify function
+  //
+  Status = gBS->CreateEvent (
+                  EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE,
+                  TPL_NOTIFY,
+                  ResetSystemLibAddressChangeEvent,
+                  NULL,
+                  &ResetSystemVirtualNotifyEvent
+                  );
+  ASSERT_EFI_ERROR (Status);
+  return Status;
+}
diff --git a/OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/DxeResetSystemAcpiGedLib.inf b/OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/DxeResetSystemAcpiGedLib.inf
new file mode 100644
index 0000000000..e54ae5e0b8
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/DxeResetSystemAcpiGedLib.inf
@@ -0,0 +1,41 @@
+## @file
+#  DXE library instance for ResetSystem library class for LoongArch.
+#
+#  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+  INF_VERSION                    = 1.29
+  BASE_NAME                      = ResetSystemLib
+  FILE_GUID                      = F05197D5-5827-AA61-FB2D-BC69259F17A9
+  MODULE_TYPE                    = DXE_RUNTIME_DRIVER
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = ResetSystemLib|DXE_DRIVER DXE_RUNTIME_DRIVER SMM_CORE DXE_SMM_DRIVER UEFI_DRIVER UEFI_APPLICATION
+  CONSTRUCTOR                    = ResetSystemLibConstructor
+
+#
+#  VALID_ARCHITECTURES           = LOONGARCH64
+#
+
+[Sources]
+  DxeResetSystemAcpiGed.c
+  ResetSystemAcpiGed.c
+
+[Packages]
+  MdeModulePkg/MdeModulePkg.dec
+  MdePkg/MdePkg.dec
+  OvmfPkg/OvmfPkg.dec
+
+[LibraryClasses]
+  BaseLib
+  DebugLib
+  DxeServicesTableLib
+  IoLib
+  UefiLib
+
+[Guids]
+  gEfiAcpi10TableGuid                           ## PRODUCES           ## SystemTable
+  gEfiAcpiTableGuid                             ## PRODUCES           ## SystemTable
diff --git a/OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/ResetSystemAcpiGed.c b/OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/ResetSystemAcpiGed.c
new file mode 100644
index 0000000000..d9283cecd5
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/ResetSystemAcpiGed.c
@@ -0,0 +1,128 @@
+/** @file
+  ResetSystem library implementation.
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Base.h>
+#include <Uefi.h>
+#include <PiPei.h>
+#include <Library/BaseLib.h>        // CpuDeadLoop()
+#include <Library/DebugLib.h>
+#include <Library/ResetSystemLib.h> // ResetCold()
+#include <Library/IoLib.h>
+#include "ResetSystemAcpiGed.h"
+
+POWER_MANAGER  mPowerManager;
+
+/**
+  Calling this function causes a system-wide reset. This sets
+  all circuitry within the system to its initial state. This type of reset
+  is asynchronous to system operation and operates without regard to
+  cycle boundaries.
+
+  System reset should not return, if it returns, it means the system does
+  not support cold reset.
+**/
+STATIC VOID
+AcpiGedReset (
+  VOID
+  )
+{
+  MmioWrite8 (
+    (UINTN)mPowerManager.ResetRegAddr,
+    mPowerManager.ResetValue
+    );
+
+  CpuDeadLoop ();
+}
+
+/**
+  This function causes the system to enter a power state equivalent
+    to the ACPI S5 states.
+
+ * */
+STATIC VOID
+AcpiGedShutdown (
+  VOID
+  )
+{
+  MmioWrite8 (
+    (UINTN)mPowerManager.SleepControlRegAddr,
+    (1 << 5) /* enable bit */ |
+    (5 << 2) /* typ == S5  */
+    );
+
+  CpuDeadLoop ();
+}
+
+/**
+  This function causes a system-wide reset (cold reset), in which
+  all circuitry within the system returns to its initial state. This type of
+  reset is asynchronous to system operation and operates without regard to
+  cycle boundaries.
+
+  If this function returns, it means that the system does not support cold
+  reset.
+**/
+VOID EFIAPI
+ResetCold (
+  VOID
+  )
+{
+  AcpiGedReset ();
+}
+
+/**
+  This function causes a system-wide initialization (warm reset), in which all
+  processors are set to their initial state. Pending cycles are not corrupted.
+
+  If this function returns, it means that the system does not support warm
+  reset.
+**/
+VOID EFIAPI
+ResetWarm (
+  VOID
+  )
+{
+  AcpiGedReset ();
+}
+
+/**
+  This function causes a systemwide reset. The exact type of the reset is
+  defined by the EFI_GUID that follows the Null-terminated Unicode string passed
+  into ResetData. If the platform does not recognize the EFI_GUID in ResetData
+  the platform must pick a supported reset type to perform.The platform may
+  optionally log the parameters from any non-normal reset that occurs.
+
+  @param[in]  DataSize   The size, in bytes, of ResetData.
+  @param[in]  ResetData  The data buffer starts with a Null-terminated string,
+                         followed by the EFI_GUID.
+**/
+VOID
+EFIAPI
+ResetPlatformSpecific (
+  IN UINTN  DataSize,
+  IN VOID   *ResetData
+  )
+{
+  AcpiGedReset ();
+}
+
+/**
+  This function causes the system to enter a power state equivalent
+  to the ACPI G2/S5 or G3 states.
+
+  If this function returns, it means that the system does not support shut down
+  reset.
+**/
+VOID EFIAPI
+ResetShutdown (
+  VOID
+  )
+{
+  AcpiGedShutdown ();
+}
diff --git a/OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/ResetSystemAcpiGed.h b/OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/ResetSystemAcpiGed.h
new file mode 100644
index 0000000000..23c722a0f1
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/ResetSystemAcpiGed.h
@@ -0,0 +1,23 @@
+/** @file
+  ResetSystem lib head file.
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef RESET_SYSTEM_ACPI_GED_H_
+#define RESET_SYSTEM_ACPI_GED_H_
+
+#include <Base.h>
+
+typedef struct {
+  UINT64    SleepControlRegAddr;
+  UINT64    SleepStatusRegAddr;
+  UINT64    ResetRegAddr;
+  UINT8     ResetValue;
+} POWER_MANAGER;
+
+extern POWER_MANAGER  mPowerManager;
+#endif // RESET_SYSTEM_ACPI_GED_H_
-- 
2.27.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#110543): https://edk2.groups.io/g/devel/message/110543
Mute This Topic: https://groups.io/mt/102342335/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* [edk2-devel] [PATCH v1 27/29] OvmfPkg/LoongArchVirt: Support SEC phase
       [not found] <20231102134249.3983594-1-lichao@loongson.cn>
                   ` (16 preceding siblings ...)
  2023-11-02 13:42 ` [edk2-devel] [PATCH v1 26/29] OvmfPkg/LoongArchVirt: Add reset system library Chao Li
@ 2023-11-02 13:42 ` Chao Li
  17 siblings, 0 replies; 18+ messages in thread
From: Chao Li @ 2023-11-02 13:42 UTC (permalink / raw)
  To: devel
  Cc: Ard Biesheuvel, Jiewen Yao, Jordan Justen, Gerd Hoffmann,
	Xianglai Li, Bibo Mao

Add SEC code for LoongArch virtual machine.

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

Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Chao Li <lichao@loongson.cn>
Co-authored-by: Xianglai Li <lixianglai@loongson.cn>
Co-authored-by: Bibo Mao <maobibo@loongson.cn>
---
 OvmfPkg/LoongArchVirt/Sec/LoongArch64/Start.S | 176 ++++++
 OvmfPkg/LoongArchVirt/Sec/SecMain.c           | 507 ++++++++++++++++++
 OvmfPkg/LoongArchVirt/Sec/SecMain.inf         |  53 ++
 3 files changed, 736 insertions(+)
 create mode 100644 OvmfPkg/LoongArchVirt/Sec/LoongArch64/Start.S
 create mode 100644 OvmfPkg/LoongArchVirt/Sec/SecMain.c
 create mode 100644 OvmfPkg/LoongArchVirt/Sec/SecMain.inf

diff --git a/OvmfPkg/LoongArchVirt/Sec/LoongArch64/Start.S b/OvmfPkg/LoongArchVirt/Sec/LoongArch64/Start.S
new file mode 100644
index 0000000000..21cc9f3388
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Sec/LoongArch64/Start.S
@@ -0,0 +1,176 @@
+#------------------------------------------------------------------------------
+#
+# Start for Loongson LoongArch processor
+#
+# Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#  @par Glossary:
+#    - CSR - CPU Status Register
+#    - EBASE - Exception Base Address
+#------------------------------------------------------------------------------
+#ifndef __ASSEMBLY__
+#define __ASSEMBLY__
+#endif
+
+#include <Library/BaseMemoryLib.h>
+#include <Register/LoongArch64/Csr.h>
+#include <Protocol/DebugSupport.h>
+
+#define BOOTCORE_ID 0
+
+ASM_GLOBAL ASM_PFX(_ModuleEntryPoint)
+ASM_PFX(_ModuleEntryPoint):
+  /* Disable interrupt */
+  li.d     $t0, (1 << 2)
+  csrxchg  $zero, $t0, LOONGARCH_CSR_CRMD
+
+  /* Read physical cpu number id */
+  bl       GetApicId
+  li.d     $t0, BOOTCORE_ID  //0
+  bne      $a0, $t0, SlaveMain
+
+  /* Configure BSP reset ebase */
+  li.d     $a0, FixedPcdGet64(PcdCpuExceptionVectorBaseAddress)
+  bl       SetExceptionBaseAddress
+  move     $t1, $a0
+
+  /* Set BSP stack */
+  li.d     $t0, FixedPcdGet64(PcdOvmfSecPeiTempRamBase) + FixedPcdGet32(PcdOvmfSecPeiTempRamSize)  # stack base
+  move     $sp, $t0
+  addi.d   $sp, $sp, -0x8
+
+  /* Construct SEC and PEI step exception environment */
+  la.pcrel $a1, ExceptionEntryStart
+  la.pcrel $t0, ExceptionEntryEnd
+  sub.d    $a2, $t0, $a1
+  li.w     $t0, (MAX_LOONGARCH_EXCEPTION +  MAX_LOONGARCH_INTERRUPT) * 512
+  bgeu     $a2, $t0, DeadLoop
+  move     $a0, $t1
+  bl       CopyMem
+
+CallEntry:
+  /* Call C function make sure parameter true */
+  li.d     $a0, FixedPcdGet64(PcdOvmfFdBaseAddress) # FW base
+  addi.d   $a1, $sp, 0x8
+  bl       SecCoreStartupWithStack
+# End of _ModuleEntryPoint
+
+ASM_PFX(ClearMailBox):
+  /* Clear mailbox */
+  li.d      $t1, LOONGARCH_IOCSR_MBUF3
+  iocsrwr.d $zero, $t1
+  li.d      $t1, LOONGARCH_IOCSR_MBUF2
+  iocsrwr.d $zero, $t1
+  li.d      $t1, LOONGARCH_IOCSR_MBUF1
+  iocsrwr.d $zero, $t1
+  li.d      $t1, LOONGARCH_IOCSR_MBUF0
+  iocsrwr.d $zero, $t1
+  jirl      $zero, $ra, 0
+# End of ClearMailBox
+
+ASM_PFX(EnableIPI):
+  /* Enable IPI interrupt */
+  li.d      $t1, (1 << 12)
+  csrxchg   $t1, $t1, LOONGARCH_CSR_ECFG
+
+  addi.d    $t2, $zero, -1
+  li.d      $t1, LOONGARCH_IOCSR_IPI_EN
+  iocsrwr.w $t2, $t1
+  jirl      $zero, $ra, 0
+# End of EeableIPI
+
+#/**
+#   Get APIC ID for every CPU.
+#
+#   @param   NULL
+#   @return  APICID
+#
+#   UINTN
+#   EFI_API
+#   GetApicId (
+#     VOID
+#     )
+#**/
+ASM_PFX(GetApicId):
+  csrrd $a0, LOONGARCH_CSR_CPUNUM
+  andi  $a0, $a0, 0x3ff
+  jirl  $zero, $ra, 0
+# End of GetApicId
+
+ASM_PFX(ApInitStack):
+  li.d   $t1, SIZE_1KB 
+  csrrd  $t0, LOONGARCH_CSR_TMID
+  mul.d  $t1, $t0, $t1
+  li.d   $t2, FixedPcdGet32(PcdCpuMaxLogicalProcessorNumber)
+  bgeu   $t0, $t2, DeadLoop
+  li.d   $t0, FixedPcdGet64(PcdOvmfSecPeiTempRamBase) + FixedPcdGet32(PcdOvmfSecPeiTempRamSize) - SIZE_64KB
+  sub.d  $sp, $t0, $t1
+  addi.d $sp, $sp, -0x8
+  jirl   $zero, $ra, 0
+# End of ApInitStack
+
+ASM_PFX(SlaveMain):
+  /* Set AP exception handle in flash */
+  la.pcrel  $a0, ApException
+  bl        SetExceptionBaseAddress
+
+  /* Clean up local mail box and open INT */
+  bl        ClearMailBox
+  bl        EnableIPI
+  bl        EnableInterrupts
+
+WaitForWake:
+  /* Wait for wakeup */
+  bl        CpuSleep
+  li.d      $t1, LOONGARCH_IOCSR_MBUF0
+  iocsrrd.w $t2, $t1
+  beqz      $t2, WaitForWake
+
+  /* Disable global interrupt */
+  bl        DisableInterrupts
+
+  /* Disable IPI interrupt */
+  li.d      $t0, (1 << 12)
+  csrxchg   $zero, $t0, LOONGARCH_CSR_ECFG
+
+  /* Read mail buf and jump to specified entry */
+  li.d      $t1, LOONGARCH_IOCSR_MBUF0
+  iocsrrd.d $t0, $t1
+  li.d      $t1, LOONGARCH_IOCSR_MBUF3
+  iocsrrd.d $a1, $t1
+  bl        ClearMailBox
+  beqz      $a1, NoParameterCall
+
+  //
+  // If the parameters are not NULL, then calling happened in FW ENV.
+  // Set the EBASE to be the same as BSP.
+  //
+  li.d      $a0, FixedPcdGet64(PcdCpuExceptionVectorBaseAddress)
+  bl        SetExceptionBaseAddress
+
+  bl        ApInitStack
+  bl        GetApicId
+NoParameterCall:
+  move      $ra, $t0
+  jirl      $zero, $ra, 0x0
+# End of SlaveMain
+
+.align 12
+ASM_PFX(ApException):
+  csrrd     $t0, LOONGARCH_CSR_ESTAT
+  srli.d    $t0, $t0, 12
+  beqz      $t0, DeadLoop
+
+  li.d      $t0, LOONGARCH_IOCSR_IPI_STATUS
+  iocsrrd.w $t1, $t0
+  li.d      $t0, LOONGARCH_IOCSR_IPI_CLEAR
+  iocsrwr.w $t1, $t0
+  ertn
+# End of ApException
+
+ASM_PFX(DeadLoop):
+  b   DeadLoop
+# End of DeadLoop
+.end
diff --git a/OvmfPkg/LoongArchVirt/Sec/SecMain.c b/OvmfPkg/LoongArchVirt/Sec/SecMain.c
new file mode 100644
index 0000000000..417b95407c
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Sec/SecMain.c
@@ -0,0 +1,507 @@
+/** @file
+  Main SEC phase code.  Transitions to PEI.
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <PiPei.h>
+
+#include <Library/PeimEntryPoint.h>
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/PeiServicesLib.h>
+#include <Library/PcdLib.h>
+#include <Library/DebugAgentLib.h>
+#include <Library/IoLib.h>
+#include <Library/PeCoffLib.h>
+#include <Library/PeCoffGetEntryPointLib.h>
+#include <Library/PeCoffExtraActionLib.h>
+#include <Library/ExtractGuidedSectionLib.h>
+
+#include <Ppi/TemporaryRamSupport.h>
+
+/**
+  temporary memory to permanent memory and do stack switching.
+
+  @param[in]  PeiServices     Pointer to the PEI Services Table.
+  @param[in]  TemporaryMemoryBase    Temporary Memory Base address.
+  @param[in]  PermanentMemoryBase   Permanent Memory Base address.
+  @param[in]  CopySize   The size of memory that needs to be migrated.
+
+  @retval   EFI_SUCCESS  Migration successful.
+**/
+EFI_STATUS
+EFIAPI
+TemporaryRamMigration (
+  IN CONST EFI_PEI_SERVICES  **PeiServices,
+  IN EFI_PHYSICAL_ADDRESS    TemporaryMemoryBase,
+  IN EFI_PHYSICAL_ADDRESS    PermanentMemoryBase,
+  IN UINTN                   CopySize
+  );
+
+EFI_PEI_TEMPORARY_RAM_SUPPORT_PPI  mTemporaryRamSupportPpi = {
+  TemporaryRamMigration
+};
+
+EFI_PEI_PPI_DESCRIPTOR  mPrivateDispatchTable[] = {
+  {
+    (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
+    &gEfiTemporaryRamSupportPpiGuid,
+    &mTemporaryRamSupportPpi
+  },
+};
+
+/**
+  Locates a section within a series of sections
+  with the specified section type.
+
+  The Instance parameter indicates which instance of the section
+  type to return. (0 is first instance, 1 is second...)
+
+  @param[in]   Sections        The sections to search
+  @param[in]   SizeOfSections  Total size of all sections
+  @param[in]   SectionType     The section type to locate
+  @param[in]   Instance        The section instance number
+  @param[out]  FoundSection    The FFS section if found
+
+  @retval EFI_SUCCESS           The file and section was found
+  @retval EFI_NOT_FOUND         The file and section was not found
+  @retval EFI_VOLUME_CORRUPTED  The firmware volume was corrupted
+**/
+EFI_STATUS
+FindFfsSectionInstance (
+  IN  VOID                       *Sections,
+  IN  UINTN                      SizeOfSections,
+  IN  EFI_SECTION_TYPE           SectionType,
+  IN  UINTN                      Instance,
+  OUT EFI_COMMON_SECTION_HEADER  **FoundSection
+  )
+{
+  EFI_PHYSICAL_ADDRESS       CurrentAddress;
+  UINT32                     Size;
+  EFI_PHYSICAL_ADDRESS       EndOfSections;
+  EFI_COMMON_SECTION_HEADER  *Section;
+  EFI_PHYSICAL_ADDRESS       EndOfSection;
+
+  //
+  // Loop through the FFS file sections within the PEI Core FFS file
+  //
+  EndOfSection  = (EFI_PHYSICAL_ADDRESS)(UINTN)Sections;
+  EndOfSections = EndOfSection + SizeOfSections;
+  for ( ; ; ) {
+    if (EndOfSection == EndOfSections) {
+      break;
+    }
+
+    CurrentAddress = (EndOfSection + 3) & ~(3ULL);
+    if (CurrentAddress >= EndOfSections) {
+      return EFI_VOLUME_CORRUPTED;
+    }
+
+    Section = (EFI_COMMON_SECTION_HEADER *)(UINTN)CurrentAddress;
+
+    Size = SECTION_SIZE (Section);
+    if (Size < sizeof (*Section)) {
+      return EFI_VOLUME_CORRUPTED;
+    }
+
+    EndOfSection = CurrentAddress + Size;
+    if (EndOfSection > EndOfSections) {
+      return EFI_VOLUME_CORRUPTED;
+    }
+
+    //
+    // Look for the requested section type
+    //
+    if (Section->Type == SectionType) {
+      if (Instance == 0) {
+        *FoundSection = Section;
+        return EFI_SUCCESS;
+      } else {
+        Instance--;
+      }
+    }
+  }
+
+  return EFI_NOT_FOUND;
+}
+
+/**
+  Locates a section within a series of sections
+  with the specified section type.
+
+  @param[in]   Sections        The sections to search
+  @param[in]   SizeOfSections  Total size of all sections
+  @param[in]   SectionType     The section type to locate
+  @param[out]  FoundSection    The FFS section if found
+
+  @retval EFI_SUCCESS           The file and section was found
+  @retval EFI_NOT_FOUND         The file and section was not found
+  @retval EFI_VOLUME_CORRUPTED  The firmware volume was corrupted
+**/
+EFI_STATUS
+FindFfsSectionInSections (
+  IN  VOID                       *Sections,
+  IN  UINTN                      SizeOfSections,
+  IN  EFI_SECTION_TYPE           SectionType,
+  OUT EFI_COMMON_SECTION_HEADER  **FoundSection
+  )
+{
+  return FindFfsSectionInstance (
+           Sections,
+           SizeOfSections,
+           SectionType,
+           0,
+           FoundSection
+           );
+}
+
+/**
+  Locates a FFS file with the specified file type and a section
+  within that file with the specified section type.
+
+  @param[in]   Fv            The firmware volume to search
+  @param[in]   FileType      The file type to locate
+  @param[in]   SectionType   The section type to locate
+  @param[out]  FoundSection  The FFS section if found
+
+  @retval EFI_SUCCESS           The file and section was found
+  @retval EFI_NOT_FOUND         The file and section was not found
+  @retval EFI_VOLUME_CORRUPTED  The firmware volume was corrupted
+**/
+EFI_STATUS
+FindFfsFileAndSection (
+  IN  EFI_FIRMWARE_VOLUME_HEADER  *Fv,
+  IN  EFI_FV_FILETYPE             FileType,
+  IN  EFI_SECTION_TYPE            SectionType,
+  OUT EFI_COMMON_SECTION_HEADER   **FoundSection
+  )
+{
+  EFI_STATUS            Status;
+  EFI_PHYSICAL_ADDRESS  CurrentAddress;
+  EFI_PHYSICAL_ADDRESS  EndOfFirmwareVolume;
+  EFI_FFS_FILE_HEADER   *File;
+  UINT32                Size;
+  EFI_PHYSICAL_ADDRESS  EndOfFile;
+
+  if (Fv->Signature != EFI_FVH_SIGNATURE) {
+    DEBUG ((DEBUG_ERROR, "FV at %p does not have FV header signature\n", Fv));
+    return EFI_VOLUME_CORRUPTED;
+  }
+
+  CurrentAddress      = (EFI_PHYSICAL_ADDRESS)(UINTN)Fv;
+  EndOfFirmwareVolume = CurrentAddress + Fv->FvLength;
+
+  //
+  // Loop through the FFS files in the Boot Firmware Volume
+  //
+  for (EndOfFile = CurrentAddress + Fv->HeaderLength; ; ) {
+    CurrentAddress = (EndOfFile + 7) & ~(7ULL);
+    if (CurrentAddress > EndOfFirmwareVolume) {
+      return EFI_VOLUME_CORRUPTED;
+    }
+
+    File = (EFI_FFS_FILE_HEADER *)(UINTN)CurrentAddress;
+    Size = *(UINT32 *)File->Size & 0xffffff;
+    if (Size < (sizeof (*File) + sizeof (EFI_COMMON_SECTION_HEADER))) {
+      return EFI_VOLUME_CORRUPTED;
+    }
+
+    EndOfFile = CurrentAddress + Size;
+    if (EndOfFile > EndOfFirmwareVolume) {
+      return EFI_VOLUME_CORRUPTED;
+    }
+
+    //
+    // Look for the request file type
+    //
+    if (File->Type != FileType) {
+      continue;
+    }
+
+    Status = FindFfsSectionInSections (
+               (VOID *)(File + 1),
+               (UINTN)EndOfFile - (UINTN)(File + 1),
+               SectionType,
+               FoundSection
+               );
+    if (!EFI_ERROR (Status) ||
+        (Status == EFI_VOLUME_CORRUPTED))
+    {
+      return Status;
+    }
+  }
+}
+
+/**
+  Locates the PEI Core entry point address
+
+  @param[in]  Fv                 The firmware volume to search
+  @param[out] PeiCoreEntryPoint  The entry point of the PEI Core image
+
+  @retval EFI_SUCCESS           The file and section was found
+  @retval EFI_NOT_FOUND         The file and section was not found
+  @retval EFI_VOLUME_CORRUPTED  The firmware volume was corrupted
+**/
+EFI_STATUS
+FindPeiCoreImageBaseInFv (
+  IN  EFI_FIRMWARE_VOLUME_HEADER  *Fv,
+  OUT  EFI_PHYSICAL_ADDRESS       *PeiCoreImageBase
+  )
+{
+  EFI_STATUS                 Status;
+  EFI_COMMON_SECTION_HEADER  *Section;
+
+  Status = FindFfsFileAndSection (
+             Fv,
+             EFI_FV_FILETYPE_PEI_CORE,
+             EFI_SECTION_PE32,
+             &Section
+             );
+  if (EFI_ERROR (Status)) {
+    Status = FindFfsFileAndSection (
+               Fv,
+               EFI_FV_FILETYPE_PEI_CORE,
+               EFI_SECTION_TE,
+               &Section
+               );
+    if (EFI_ERROR (Status)) {
+      DEBUG ((DEBUG_ERROR, "Unable to find PEI Core image\n"));
+      return Status;
+    }
+  }
+
+  *PeiCoreImageBase = (EFI_PHYSICAL_ADDRESS)(UINTN)(Section + 1);
+  return EFI_SUCCESS;
+}
+
+/**
+  Find and return Pei Core entry point.
+
+  It also find SEC and PEI Core file debug information. It will report them if
+  remote debug is enabled.
+**/
+VOID
+FindAndReportEntryPoints (
+  IN  EFI_FIRMWARE_VOLUME_HEADER  **BootFirmwareVolumePtr,
+  OUT EFI_PEI_CORE_ENTRY_POINT    *PeiCoreEntryPoint
+  )
+{
+  EFI_STATUS                    Status;
+  EFI_PHYSICAL_ADDRESS          PeiCoreImageBase = 0;
+  PE_COFF_LOADER_IMAGE_CONTEXT  ImageContext;
+
+  Status = FindPeiCoreImageBaseInFv (*BootFirmwareVolumePtr, &PeiCoreImageBase);
+  ASSERT (Status == EFI_SUCCESS);
+
+  ZeroMem ((VOID *)&ImageContext, sizeof (PE_COFF_LOADER_IMAGE_CONTEXT));
+
+  //
+  // Report PEI Core debug information when remote debug is enabled
+  //
+  ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)PeiCoreImageBase;
+  ImageContext.PdbPointer   = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageContext.ImageAddress);
+  PeCoffLoaderRelocateImageExtraAction (&ImageContext);
+
+  //
+  // Find PEI Core entry point
+  //
+  Status = PeCoffLoaderGetEntryPoint ((VOID *)(UINTN)PeiCoreImageBase, (VOID **)PeiCoreEntryPoint);
+  if (EFI_ERROR (Status)) {
+    *PeiCoreEntryPoint = 0;
+  }
+
+  return;
+}
+
+/**
+  Find the peicore entry point and jump to the entry point to execute.
+
+  @param[in] Context    The first input parameter of InitializeDebugAgent().
+**/
+VOID
+EFIAPI
+SecStartupPhase2 (
+  IN VOID  *Context
+  )
+{
+  EFI_SEC_PEI_HAND_OFF        *SecCoreData;
+  EFI_FIRMWARE_VOLUME_HEADER  *BootFv;
+  EFI_PEI_CORE_ENTRY_POINT    PeiCoreEntryPoint;
+
+  SecCoreData = (EFI_SEC_PEI_HAND_OFF *)Context;
+
+  //
+  // Find PEI Core entry point. It will report SEC and Pei Core debug information if remote debug
+  // is enabled.
+  //
+  BootFv = (EFI_FIRMWARE_VOLUME_HEADER *)SecCoreData->BootFirmwareVolumeBase;
+  FindAndReportEntryPoints (&BootFv, &PeiCoreEntryPoint);
+  SecCoreData->BootFirmwareVolumeBase = BootFv;
+  SecCoreData->BootFirmwareVolumeSize = (UINTN)BootFv->FvLength;
+
+  DEBUG ((DEBUG_INFO, "Find Pei EntryPoint=%p\n", PeiCoreEntryPoint));
+
+  //
+  // Transfer the control to the PEI core
+  //
+  DEBUG ((DEBUG_INFO, "SecStartupPhase2 %p\n", PeiCoreEntryPoint));
+
+  (*PeiCoreEntryPoint)(SecCoreData, (EFI_PEI_PPI_DESCRIPTOR *)&mPrivateDispatchTable);
+
+  //
+  // If we get here then the PEI Core returned, which is not recoverable.
+  //
+  ASSERT (FALSE);
+  CpuDeadLoop ();
+}
+
+/**
+  Entry point to the C language phase of SEC. initialize some temporary memory and set up the stack,
+  the control is transferred to this function.
+
+  @param[in]  BootFv   The pointer to the PEI FV in memory.
+  @param[in]  TopOfCurrentStack  Top of Current Stack.
+**/
+VOID
+EFIAPI
+SecCoreStartupWithStack (
+  IN EFI_FIRMWARE_VOLUME_HEADER  *BootFv,
+  IN VOID                        *TopOfCurrentStack
+  )
+{
+  EFI_SEC_PEI_HAND_OFF        SecCoreData;
+  EFI_FIRMWARE_VOLUME_HEADER  *BootPeiFv = (EFI_FIRMWARE_VOLUME_HEADER *)BootFv;
+
+  DEBUG ((DEBUG_INFO, "Entering C environment\n"));
+
+  ProcessLibraryConstructorList (NULL, NULL);
+
+  DEBUG ((
+    DEBUG_INFO,
+    "SecCoreStartupWithStack (0x%lx, 0x%lx)\n",
+    (UINTN)BootFv,
+    (UINTN)TopOfCurrentStack
+    ));
+  DEBUG ((
+    DEBUG_INFO,
+    "(0x%lx, 0x%lx)\n",
+    (UINTN)(FixedPcdGet64 (PcdOvmfSecPeiTempRamBase)),
+    (UINTN)(FixedPcdGet32 (PcdOvmfSecPeiTempRamSize))
+    ));
+
+  // |-------------|       <-- TopOfCurrentStack
+  // |  BSP Stack  | 32k
+  // |-------------|
+  // |  BSP Heap   | 32k
+  // |-------------|       <-- SecCoreData.TemporaryRamBase
+  // |  Ap Stack   | 384k
+  // |-------------|
+  // |  Exception  | 64k
+  // |-------------|       <-- PcdOvmfSecPeiTempRamBase
+
+  ASSERT (
+    (UINTN)(FixedPcdGet64 (PcdOvmfSecPeiTempRamBase) +
+            FixedPcdGet32 (PcdOvmfSecPeiTempRamSize)) ==
+    (UINTN)TopOfCurrentStack
+    );
+
+  //
+  // Initialize SEC hand-off state
+  //
+  SecCoreData.DataSize = sizeof (EFI_SEC_PEI_HAND_OFF);
+
+  SecCoreData.TemporaryRamSize = (UINTN)SIZE_64KB;
+  SecCoreData.TemporaryRamBase = (VOID *)(FixedPcdGet64 (PcdOvmfSecPeiTempRamBase) + FixedPcdGet32 (PcdOvmfSecPeiTempRamSize) - SecCoreData.TemporaryRamSize);
+
+  SecCoreData.PeiTemporaryRamBase = SecCoreData.TemporaryRamBase;
+  SecCoreData.PeiTemporaryRamSize = SecCoreData.TemporaryRamSize >> 1;
+
+  SecCoreData.StackBase = (UINT8 *)SecCoreData.TemporaryRamBase + SecCoreData.PeiTemporaryRamSize;
+  SecCoreData.StackSize = SecCoreData.TemporaryRamSize >> 1;
+
+  SecCoreData.BootFirmwareVolumeBase = BootPeiFv;
+  SecCoreData.BootFirmwareVolumeSize = (UINTN)BootPeiFv->FvLength;
+
+  DEBUG ((
+    DEBUG_INFO,
+    "&SecCoreData.BootFirmwareVolumeBase=%lx SecCoreData.BootFirmwareVolumeBase=%lx\n",
+    (UINT64)&(SecCoreData.BootFirmwareVolumeBase),
+    (UINT64)(SecCoreData.BootFirmwareVolumeBase)
+    ));
+  DEBUG ((
+    DEBUG_INFO,
+    "&SecCoreData.BootFirmwareVolumeSize=%lx SecCoreData.BootFirmwareVolumeSize=%lx\n",
+    (UINT64)&(SecCoreData.BootFirmwareVolumeSize),
+    (UINT64)(SecCoreData.BootFirmwareVolumeSize)
+    ));
+
+  //
+  // Initialize Debug Agent to support source level debug in SEC/PEI phases before memory ready.
+  //
+  InitializeDebugAgent (DEBUG_AGENT_INIT_PREMEM_SEC, NULL, NULL);
+  SecStartupPhase2 (&SecCoreData);
+}
+
+/**
+  temporary memory to permanent memory and do stack switching.
+
+  @param[in]  PeiServices     Pointer to the PEI Services Table.
+  @param[in]  TemporaryMemoryBase    Temporary Memory Base address.
+  @param[in]  PermanentMemoryBase   Permanent Memory Base address.
+  @param[in]  CopySize   The size of memory that needs to be migrated.
+
+  @retval   EFI_SUCCESS  Migration successful.
+**/
+EFI_STATUS
+EFIAPI
+TemporaryRamMigration (
+  IN CONST EFI_PEI_SERVICES  **PeiServices,
+  IN EFI_PHYSICAL_ADDRESS    TemporaryMemoryBase,
+  IN EFI_PHYSICAL_ADDRESS    PermanentMemoryBase,
+  IN UINTN                   CopySize
+  )
+{
+  VOID                      *OldHeap;
+  VOID                      *NewHeap;
+  VOID                      *OldStack;
+  VOID                      *NewStack;
+  BASE_LIBRARY_JUMP_BUFFER  JumpBuffer;
+
+  DEBUG ((
+    DEBUG_INFO,
+    "TemporaryRamMigration (0x%Lx, 0x%Lx, 0x%Lx)\n",
+    TemporaryMemoryBase,
+    PermanentMemoryBase,
+    (UINT64)CopySize
+    ));
+
+  OldHeap = (VOID *)(UINTN)TemporaryMemoryBase;
+  NewHeap = (VOID *)((UINTN)PermanentMemoryBase + (CopySize >> 1));
+
+  OldStack = (VOID *)((UINTN)TemporaryMemoryBase + (CopySize >> 1));
+  NewStack = (VOID *)(UINTN)PermanentMemoryBase;
+
+  //
+  // Migrate Heap
+  //
+  CopyMem (NewHeap, OldHeap, CopySize >> 1);
+
+  //
+  // Migrate Stack
+  //
+  CopyMem (NewStack, OldStack, CopySize >> 1);
+
+  // Use SetJump ()/LongJump () to switch to a new stack.
+  //
+  if (SetJump (&JumpBuffer) == 0) {
+    JumpBuffer.SP = JumpBuffer.SP - (UINTN)OldStack + (UINTN)NewStack;
+    LongJump (&JumpBuffer, (UINTN)-1);
+  }
+
+  return EFI_SUCCESS;
+}
diff --git a/OvmfPkg/LoongArchVirt/Sec/SecMain.inf b/OvmfPkg/LoongArchVirt/Sec/SecMain.inf
new file mode 100644
index 0000000000..d528aae02b
--- /dev/null
+++ b/OvmfPkg/LoongArchVirt/Sec/SecMain.inf
@@ -0,0 +1,53 @@
+## @file
+#  SEC Driver
+#
+#  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = SecMain
+  FILE_GUID                      = 57d02d4f-5a5d-4bfa-b7d6-ba0a4d2c72ce
+  MODULE_TYPE                    = SEC
+  VERSION_STRING                 = 1.0
+
+#
+#  VALID_ARCHITECTURES           = LOONGARCH64
+#
+
+[Sources]
+  LoongArch64/Start.S
+  SecMain.c
+
+[Packages]
+  OvmfPkg/OvmfPkg.dec
+  MdePkg/MdePkg.dec
+  MdeModulePkg/MdeModulePkg.dec
+  UefiCpuPkg/UefiCpuPkg.dec
+
+[LibraryClasses]
+  BaseLib
+  DebugLib
+  BaseMemoryLib
+  PcdLib
+  DebugAgentLib
+  IoLib
+  PeCoffLib
+  PeCoffGetEntryPointLib
+  PeCoffExtraActionLib
+  CpuExceptionHandlerLib
+
+[Ppis]
+  gEfiTemporaryRamSupportPpiGuid                # PPI ALWAYS_PRODUCED
+
+[FixedPcd]
+  gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamBase
+  gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamSize
+
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuExceptionVectorBaseAddress
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber
+
+  gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFdBaseAddress
-- 
2.27.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#110535): https://edk2.groups.io/g/devel/message/110535
Mute This Topic: https://groups.io/mt/102342216/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

end of thread, other threads:[~2023-11-02 13:52 UTC | newest]

Thread overview: 18+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
     [not found] <20231102134249.3983594-1-lichao@loongson.cn>
2023-11-02 13:42 ` [edk2-devel] [PATCH v1 02/29] MdePkg: Add LoongArch64 FPU function set into BaseCpuLib Chao Li
2023-11-02 13:42 ` [edk2-devel] [PATCH v1 03/29] MdePkg: Add LoongArch64 exception function set into BaseLib Chao Li
2023-11-02 13:42 ` [edk2-devel] [PATCH v1 05/29] MdePkg: Add LoongArch Cpucfg function Chao Li
2023-11-02 13:42 ` [edk2-devel] [PATCH v1 06/29] MdePkg: Add read stable counter operation for LoongArch Chao Li
2023-11-02 13:42 ` [edk2-devel] [PATCH v1 08/29] MdePkg: Add IOCSR " Chao Li
2023-11-02 13:42 ` [edk2-devel] [PATCH v1 09/29] UefiCpuPkg: Add LoongArch64 CPU Timer library Chao Li
2023-11-02 13:42 ` [edk2-devel] [PATCH v1 11/29] UefiCpuPkg: Add CpuMmuLib.h to UefiCpuPkg Chao Li
2023-11-02 13:42 ` [edk2-devel] [PATCH v1 15/29] EmbeddedPkg: Add PcdPrePiCpuIoSize width for LOONGARCH64 Chao Li
2023-11-02 13:42 ` [edk2-devel] [PATCH v1 16/29] ArmVirtPkg: Move PCD of FDT base address and FDT padding to OvmfPkg Chao Li
2023-11-02 13:42 ` [edk2-devel] [PATCH v1 17/29] OvmfPkg/LoongArchVirt: Add PciCpuIo2Dxe module Chao Li
2023-11-02 13:42 ` [edk2-devel] [PATCH v1 18/29] OvmfPkg/LoongArchVirt: Add stable timer driver Chao Li
2023-11-02 13:42 ` [edk2-devel] [PATCH v1 19/29] OvmfPkg/LoongArchVirt: Add a NULL library named CollectApResouceLibNull Chao Li
2023-11-02 13:42 ` [edk2-devel] [PATCH v1 21/29] OvmfPkg/LoongArchVirt: Add real time clock library Chao Li
2023-11-02 13:42 ` [edk2-devel] [PATCH v1 23/29] OvmfPkg/LoongArchVirt: Add PeiServiceTablePointerLib Chao Li
2023-11-02 13:42 ` [edk2-devel] [PATCH v1 24/29] OvmfPkg/LoongArchVirt: Add platform boot manager library Chao Li
2023-11-02 13:42 ` [edk2-devel] [PATCH v1 25/29] OvmfPkg/LoongArchVirt: Add FdtQemuFwCfgLib Chao Li
2023-11-02 13:42 ` [edk2-devel] [PATCH v1 26/29] OvmfPkg/LoongArchVirt: Add reset system library Chao Li
2023-11-02 13:42 ` [edk2-devel] [PATCH v1 27/29] OvmfPkg/LoongArchVirt: Support SEC phase Chao Li

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